package com.movitech.mobile.cz.base.purchase.bizservice.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.movitech.mobile.cz.base.bizconfig.entity.SStrategicCategory;
import com.movitech.mobile.cz.base.bizconfig.entity.SSuppliersCategory;
import com.movitech.mobile.cz.base.bizconfig.entity.SSuppliersCategoryTemplate;
import com.movitech.mobile.cz.base.bizconfig.service.SStrategicCategoryService;
import com.movitech.mobile.cz.base.bizconfig.service.SSuppliersCategoryService;
import com.movitech.mobile.cz.base.bizconfig.service.SSuppliersCategoryTemplateService;
import com.movitech.mobile.cz.base.common.aop.ServiceThrowable;
import com.movitech.mobile.cz.base.common.bpm.*;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.*;
import com.movitech.mobile.cz.base.common.utils.IdGen;
import com.movitech.mobile.cz.base.modules.activiti.entity.AProcessConfig;
import com.movitech.mobile.cz.base.modules.activiti.entity.AProcessNodeConfig;
import com.movitech.mobile.cz.base.modules.activiti.entity.AProcessNodeLineConfig;
import com.movitech.mobile.cz.base.modules.activiti.service.*;
import com.movitech.mobile.cz.base.modules.config.*;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.purchase.bizservice.ExtWFlowFormStrategicProtocolService;
import com.movitech.mobile.cz.base.purchase.bizservice.WorkFlowService;
import com.movitech.mobile.cz.base.purchase.bizvo.*;
import com.movitech.mobile.cz.base.purchase.bizvo.purchase.AnswerNodeBasisVO;
import com.movitech.mobile.cz.base.purchase.bizvo.purchase.NodeClickVo;
import com.movitech.mobile.cz.base.purchase.bizvo.purchase.TechnicaBidScoreReqVO;
import com.movitech.mobile.cz.base.purchase.bizvo.purchase.UpdateOperatorVO;
import com.movitech.mobile.cz.base.purchase.entity.*;
import com.movitech.mobile.cz.base.purchase.entity.ext.*;
import com.movitech.mobile.cz.base.purchase.entity.resultType.IdName;
import com.movitech.mobile.cz.base.purchase.mapper.ext.ExtWFlowFormMapper;
import com.movitech.mobile.cz.base.purchase.service.*;
import com.movitech.mobile.cz.base.purchase.threadlocal.ThreadLocalWFlowFormSteps;
import com.movitech.mobile.cz.base.sessionuser.SessionUserVo;
import com.movitech.mobile.cz.base.supplier.bizvo.FlowTurnVO;
import com.movitech.mobile.cz.base.supplier.bizvo.PurchaseMbsCallBackVO;
import com.movitech.mobile.cz.base.supplier.entity.SCommentConfig;
import com.movitech.mobile.cz.base.supplier.entity.SHistoryComment;
import com.movitech.mobile.cz.base.supplier.entity.SMyDeals;
import com.movitech.mobile.cz.base.supplier.entity.SSuppliers;
import com.movitech.mobile.cz.base.supplier.entity.ext.ExtSHistoryComment;
import com.movitech.mobile.cz.base.supplier.service.*;
import com.movitech.mobile.cz.base.syndata.SynDataService;
import com.movitech.mobile.cz.base.syndata.SynSourcingDataVo;
import com.movitech.mobile.cz.base.syndata.SynSourcingDepositDataVo;
import com.movitech.mobile.cz.base.sys.bizvo.AttachmentVO;
import com.movitech.mobile.cz.base.sys.entity.*;
import com.movitech.mobile.cz.base.sys.service.*;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("workFlowService")
public class WorkFlowServiceImpl implements WorkFlowService {
    private final static Logger logger = Logger.getLogger(WorkFlowServiceImpl.class);
    @Autowired
    private BpmUtil bpmUtil;
    @Autowired
    private WFlowFormService wFlowFormService;
    @Autowired
    private WFlowFormTimeNodeService wFlowFormTimeNodeService;

    @Autowired
    private PSpecialPurchasePlanService pSpecialPurchasePlanService;

    @Autowired
    private PContactPlanService pContactPlanService;
    @Autowired
    private WFlowFormTechScoreDetalsService wFlowFormTechScoreDetalsService;

    @Autowired
    private SSuppliersCategoryTemplateService sSuppliersCategoryTemplateService;

    @Autowired
    private AProcessConfigService aProcessConfigService;
    @Autowired
    private ActivitiRuntimeService activitiRuntimeService;
    @Autowired
    private ActivitiTaskService activitiTaskService;
    @Autowired
    private AProcessNodeConfigService aProcessNodeConfigService;

    @Autowired
    private AProcessNodeLineConfigService aProcessNodeLineConfigService;

    @Autowired
    private ExtWFlowFormMapper extWFlowFormMapper;

    @Autowired
    private SMyDealsService sMyDealsService;

    @Autowired
    private SHistoryCommentService sHistoryCommentService;

    @Autowired
    private WFlowFormStepsService wFlowFormStepsService;

    @Autowired
    private SCommentConfigService sCommentConfigService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private WFlowFormTimeNodeService wlowFormTimeNodeService;

    @Autowired
    private WFlowFormBackBidService wFlowFormBackBidService;

    @Autowired
    private WFlowFormBidCandidateUnitService wFlowFormBidCandidateUnitService;
    @Autowired
    private WFlowFormSupplierEntryService wFlowFormSupplierEntryService;
    @Autowired
    private WFlowFormHistoryPriceService wFlowFormHistoryPriceService;

    @Autowired
    private WFlowFormPurchaseTeamService wFlowFormPurchaseTeamService;

    @Autowired
    private SAttachmentService sAttachmentService;

    @Autowired
    private SSuppliersService sSuppliersService;

    @Autowired
    private WFlowFormAwardBidService wFlowFormAwardBidService;

    @Autowired
    private WFlowFormCashDepositService wFlowFormCashDepositService;

    @Autowired
    private SMessagesService sMessagesService;

    @Autowired
    private SMessageTemplateService sMessageTemplateService;

    @Autowired
    private WFlowFormStrategicProtocolService wlowFormStrategicProtocolService;
    @Autowired
    private ExtWFlowFormStrategicProtocolService extwlowFormStrategicProtocolService;

    @Autowired
    private WFlowFormBidDelayHistoryService wFlowFormBidDelayHistoryService;
    @Autowired
    private WFlowFormSendBidService wFlowFormSendBidService;
    @Autowired
    private WFlowFormQuestionAnswerService wFlowFormQuestionAnswerService;
    @Autowired
    private WFlowFormAddendumReferersService wFlowFormAddendumReferersService;

    @Autowired
    private WFlowFormQaCountSignService wFlowFormQaCountSignService;

    @Autowired
    private WFlowFormSuppliersQuestionService wFlowFormSuppliersQuestionService;
    @Autowired
    private WFlowFormIbTechScoreService wFlowFormIbTechScoreService;

    @Autowired
    private WFlowFormInquiringBidService wFlowFormInquiringBidService;
    @Autowired
    private WFlowFormDiscussionHistoryService wFlowFormDiscussionHistoryService;
    @Autowired
    private WFlowFormBidNoticeThanksService wFlowFormBidNoticeThanksService;
    @Autowired
    private WFlowSubFormService wFlowSubFormService;
    @Autowired
    private WFlowFormExtMngService wFlowFormExtMngService;

    @Autowired
    private WFlowFormExtSubMngService wFlowFormExtSubMngService;
    @Autowired
    private WStrategicProtocolService wStrategicProtocolService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SProjectService sProjectService;
    @Autowired
    private SSuppliersCategoryService sSuppliersCategoryService;
    @Autowired
    private SAbutmentLogsService sAbutmentLogsService;
    @Autowired
    private SStrategicCategoryService sStrategicCategoryService;

    @Autowired
    private PSpOverallPlanDetailService pSpOverallPlanDetailService;
    @Autowired
    private PStrategicPurchaseContactService pStrategicPurchaseContactService;
    @Autowired
    private SSupplierQualificationGradeService sSupplierQualificationGradeService;
    @Autowired
    private SCompanyService sCompanyService;
    @Autowired
    private SynDataService synDataService;


    /**
     * 删除采购列表
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public boolean deleteById(String id) {
        try {
            WFlowForm wFlowForm = wFlowFormService.selectById(id);
            WFlowSubForm wFlowSubForm = wFlowSubFormService.selectByFormId(id);
            if (!(StringUtils.containsIgnoreCase("," + wFlowForm.getFlowFormSubStatus() + ",", "," + WorkFlowLineStatusEnum.LINE_STATUS_PURCHASE_SCHEME.getCode() + ",")) ||
                    (wFlowSubForm != null && wFlowSubForm.getPurchaseSolutionStatus() == PurchaseNodeButtonStatusEnum.PURCHASE_NODE_1_STATUS_2.getCode())) {
                throw new RuntimeException("当前不是可删除状态", new ServiceThrowable());
            }
            WFlowForm wFlowForm1 = new WFlowForm();
            wFlowForm1.setId(id);
            wFlowForm1.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.YES_INTEGER, false);
            wFlowFormService.updateById(wFlowForm1);
            String planId = wFlowForm.getPurchasePlanId();
            if (wFlowForm.getPurchasePlanType() == PurchaseCommonEnum.PURCHASE_PLAN_TYPE_SPECIAL.getCode()) {
                PSpecialPurchasePlan pSpecialPurchasePlan = new PSpecialPurchasePlan();
                pSpecialPurchasePlan.setId(planId);
                pSpecialPurchasePlan.setPlanStatus(PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_3.getCode());
                pSpecialPurchasePlanService.updatePSpecialPurchasePlan(pSpecialPurchasePlan);
            } else {
                PStrategicPurchaseContact pStrategicPurchaseContact = new PStrategicPurchaseContact();
                pStrategicPurchaseContact.setId(planId);
                pStrategicPurchaseContact.setPurchaseItemStatus(PurchaseCommonEnum.P_OVER_PLAN_STATUS_3.getCode());
                pStrategicPurchaseContactService.updateById(pStrategicPurchaseContact);
            }
            sMyDealsService.deleteNoDonedByFormId(id);

            ///
            //通知招标项状态
            SynSourcingDataVo synSourcingDataVo = new SynSourcingDataVo();
            synSourcingDataVo.setSrId(wFlowForm.getContractId());
            synSourcingDataVo.setSrStatus("0");
            synDataService.changeSourcingStatus(synSourcingDataVo);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("============deleteById=======e:========" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 根据formId查询代办
     *
     * @param vo
     * @return
     */
    @Override
    public SMyDeals selectDeals(NodeClickVo vo) {
        SMyDeals sMyDeals = new SMyDeals();
        sMyDeals.setRelatedId(vo.getFormId());
        sMyDeals.setSubRelatedId(vo.getSubId());
        Integer nodeType = vo.getNodeCode();
        if (nodeType == null) {
            WFlowForm wFlowForm = wFlowFormService.selectById(vo.getFormId());
            String subSatus = wFlowForm.getFlowFormSubStatus();
            try {
                nodeType = Integer.parseInt(subSatus);
            } catch (NumberFormatException e) {
                String[] status = subSatus.split(",");
                nodeType = Integer.parseInt(status[status.length - 1]);
            }
        }
        if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_PURCHASE_SCHEME.getCode()) {//采购方案
            sMyDeals.setDealSubType(MyDealSubTypeEnum.PURCHASE_PLAN.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.PURCHASE_PLAN.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_SUPPLIER_ENTRY.getCode()) {//供应商入围
            sMyDeals.setDealSubType(MyDealSubTypeEnum.SUPPLIER_ENTRY.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.SUPPLIER_ENTRY.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_BID_DOC.getCode()) {//招标文件
            sMyDeals.setDealSubType(MyDealSubTypeEnum.BIDDING_DOCUMENTS.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.BIDDING_DOCUMENTS.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_SEND_BID.getCode()) {//发标
            sMyDeals.setDealSubType(MyDealSubTypeEnum.SEND_BID.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.SEND_BID.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_ANSWER_ADDENDUM.getCode()) {//答疑补遗
            sMyDeals.setDealSubType(MyDealSubTypeEnum.QUE_ANSWER.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.QUE_ANSWER.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_BACK_BID.getCode()) {//回标
            sMyDeals.setDealSubType(MyDealSubTypeEnum.RETURN_BID.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.RETURN_BID.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_TWO_BACK_BID.getCode()) {//二轮回标
            sMyDeals.setDealSubType(MyDealSubTypeEnum.TWO_RETURN_BID.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.TWO_RETURN_BID.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_OPEN_BID.getCode()) {//开标
            sMyDeals.setDealSubType(MyDealSubTypeEnum.OPEN_BID.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.OPEN_BID.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_TENDER_BID.getCode()) {//询标
            sMyDeals.setDealSubType(MyDealSubTypeEnum.INQUIRING_BID.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.INQUIRING_BID.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_BUSINESS_NEGOTIATION.getCode()) {//商务谈判
            sMyDeals.setDealSubType(MyDealSubTypeEnum.BUSINESS_NEGOTIATION.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.BUSINESS_NEGOTIATION.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_EVALUATE_BID.getCode()) {//评标
            sMyDeals.setDealSubType(MyDealSubTypeEnum.PING_BID.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.PING_BID.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_CALIBRATION_BID.getCode()) {//定标
            sMyDeals.setDealSubType(MyDealSubTypeEnum.CALIBRATION.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.CALIBRATION.getCode());
        } else if (nodeType == WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode()) {//流标
            sMyDeals.setDealSubType(MyDealSubTypeEnum.ABORTIVE_LOOK_THROUGH.getCode());
            sMyDeals.setActionType(MyDealActionTypeEnum.ABORTIVE_LOOK_THROUGH.getCode());
        }
        return sMyDealsService.selectOneByEntity(sMyDeals);
    }


    /**
     * 查询节点list
     *
     * @param formId
     * @return
     */
    @Override
    public HeaderVO selectHeaderList(String formId) {
        HeaderVO headerVO = new HeaderVO();
        List<AprocessNodeConfigVO> list = Lists.newArrayList();
        headerVO.setAprocessNodeConfigVOS(list);
        WFlowForm wFlowForm = wFlowFormService.selectById(formId);
        Integer planType = wFlowForm.getBackBidRounds() == null ? 0 : wFlowForm.getBackBidRounds();
        headerVO.setFlowForm(wFlowForm);
        headerVO.setFlowSubForm(wFlowSubFormService.selectByFormId(formId));
        List<AProcessNodeConfig> lstAProcessNodeConfig = aProcessNodeConfigService.getAProcessNodeConfigByProcessConfigId(wFlowForm.getProcessConfigId());
        List<AProcessNodeLineConfig> lstAProcessNodeLineConfig = aProcessNodeLineConfigService.getAProcessNodeLineConfigByProcessConfigId(wFlowForm.getProcessConfigId());
        Map<Integer, Integer> map = wFlowFormStepsService.getNodeStatusByFormId(formId);
        for (AProcessNodeConfig aProcessNodeConfig : lstAProcessNodeConfig) {
            if (aProcessNodeConfig.getNodeType() == 1) {
                for (AProcessNodeLineConfig aProcessNodeLineConfig : lstAProcessNodeLineConfig) {
                    if (aProcessNodeLineConfig.getLineStatus() == 12 || aProcessNodeLineConfig.getLineStatus() == 0) {
                        continue;
                    }
                    if (org.apache.commons.lang3.StringUtils.equalsIgnoreCase(aProcessNodeConfig.getId(), aProcessNodeLineConfig.getToNodeConfigId())) {
                        if (aProcessNodeLineConfig.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_TWO_BACK_BID.getCode() && (planType == PurchaseCommonEnum.BACK_ROUND_1.getCode() ||
                                planType == PurchaseCommonEnum.BACK_ROUND_2.getCode() || planType == PurchaseCommonEnum.BACK_ROUND_5.getCode())) {
                            continue;
                        } else if (aProcessNodeLineConfig.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_BUSINESS_NEGOTIATION.getCode() && (planType == PurchaseCommonEnum.BACK_ROUND_1.getCode() ||
                                planType == PurchaseCommonEnum.BACK_ROUND_4.getCode())) {
                            continue;
                        }
                        Integer lineStatus = map.get(aProcessNodeLineConfig.getLineStatus());
                        Integer status = lineStatus == null ? 3 : lineStatus == 0 ? 2 : 1;
                        AprocessNodeConfigVO aprocessNodeConfigVO = new AprocessNodeConfigVO();
                        aprocessNodeConfigVO.setNodeCode(aProcessNodeLineConfig.getLineStatus());
                        aprocessNodeConfigVO.setNodeSort(aProcessNodeConfig.getNodeSort());
                        aprocessNodeConfigVO.setNodeName(aProcessNodeConfig.getNodeName());
                        aprocessNodeConfigVO.setNodeStatus(status);
                        list.add(aprocessNodeConfigVO);
                        break;
                    }
                }
            }
        }
        Collections.sort(list, new Comparator<AprocessNodeConfigVO>() {
            @Override
            public int compare(AprocessNodeConfigVO o1, AprocessNodeConfigVO o2) {
                return o1.getNodeSort() - o2.getNodeSort();
            }
        });
        return headerVO;
    }

    /**
     * 采购列表
     *
     * @param wFowFormListReqVO
     * @return
     */
    @Override
    public Page<ExtWFlowForm> findWorkFlowList(Page<ExtWFlowForm> page, WFowFormListReq wFowFormListReqVO) {
        try {
            List<ExtWFlowForm> data = extWFlowFormMapper.selectExtList(page, wFowFormListReqVO);
            String wfStatus = wFowFormListReqVO.getFlowFormStatus();
            if (StringUtils.isNotEmpty(wfStatus)) {
                wFowFormListReqVO.setStatusList(StringUtils.getListBySplitStr(wfStatus));
            }
            //parseExtWFowForm(data);
            page.setRecords(data);
            return page;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }

    @Override
    public Page<ExtWFlowForm> findSimWorkFlowList(Page<ExtWFlowForm> page, WFowFormListReq wFowFormListReqVO) {
        try {
            List<ExtWFlowForm> data = extWFlowFormMapper.selectSimList(page, wFowFormListReqVO);
            String wfStatus = wFowFormListReqVO.getFlowFormStatus();
            if (StringUtils.isNotEmpty(wfStatus)) {
                wFowFormListReqVO.setStatusList(StringUtils.getListBySplitStr(wfStatus));
            }
            //parseExtWFowForm(data);
            page.setRecords(data);
            return page;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 采购方案节点数据
     *
     * @param wflowFormId
     * @return
     */
    @Override
    public PurchasePlanNodeAllDataResVO selectPurchasePlanNodeData(String wflowFormId) {

        PurchasePlanNodeAllDataResVO purchasePlanNodeAllDataResVO = new PurchasePlanNodeAllDataResVO();
        WFowFormListReq wFlowForm = new WFowFormListReq();
        wFlowForm.setId(wflowFormId);
        List<ExtWFlowForm> data = extWFlowFormMapper.selectExtList(wFlowForm);
        parseExtWFowForm(data);
        ExtWFlowForm extWFlowForm = data.get(0);
        if (extWFlowForm.getPurchasePlanType() == PurchaseCommonEnum.PURCHASE_PLAN_TYPE_SPECIAL.getCode()) {
            if (StringUtils.isNotEmpty(extWFlowForm.getContractId())) {
                Double price = pContactPlanService.getBudgetByContractId(extWFlowForm.getContractId());
                if (extWFlowForm.getPurchaseType() == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_4.getCode()) {
                    if (price == null || price < 300000) {
                        extWFlowForm.setPlanBudgetPricesName(BudgetPriceEnum.budget_price_1.getDesc());
                    } else {
                        extWFlowForm.setPlanBudgetPricesName(BudgetPriceEnum.budget_price_2.getDesc());
                    }
                } else {
                    if ("1".equals(extWFlowForm.getPurchaseClassification())) {
                        if (price == null || price < 10000000) {
                            extWFlowForm.setPlanBudgetPricesName(BudgetPriceEnum.budget_price_5.getDesc());
                        } else {
                            extWFlowForm.setPlanBudgetPricesName(BudgetPriceEnum.budget_price_6.getDesc());
                        }
                    } else {
                        if (price == null || price < 3000000) {
                            extWFlowForm.setPlanBudgetPricesName(BudgetPriceEnum.budget_price_3.getDesc());
                        } else {
                            extWFlowForm.setPlanBudgetPricesName(BudgetPriceEnum.budget_price_4.getDesc());
                        }
                    }
                }
            }
        }

        purchasePlanNodeAllDataResVO.setExtWFowForm(extWFlowForm);

        purchasePlanNodeAllDataResVO.setWflowFormHistoryPrices(wFlowFormHistoryPriceService.getByFlowFormId(wflowFormId));
        WFlowFormBidCandidateUnit wFlowFormBidCandidateUnit = new WFlowFormBidCandidateUnit();
        wFlowFormBidCandidateUnit.setFlowFormId(wflowFormId);
        wFlowFormBidCandidateUnit.setCandidateType(PurchaseCommonEnum.CANDIDATE_TYPE_PUT.getCode());
        List<ExtWFlowFormBidCandidateUnit> extWFlowFormBidCandidateUnits = wFlowFormBidCandidateUnitService
                .getExtFormList(wFlowFormBidCandidateUnit);
        purchasePlanNodeAllDataResVO.setExtWFlowFormBidCandidateUnits(extWFlowFormBidCandidateUnits);

        purchasePlanNodeAllDataResVO.setWflowFormTimeNode(wlowFormTimeNodeService.selectByFlowFormId(wflowFormId));

        purchasePlanNodeAllDataResVO.setWflowFormPurchaseTeams(wFlowFormPurchaseTeamService.getTeamByFlowFormId(wflowFormId));

        purchasePlanNodeAllDataResVO.setSattachments(sAttachmentService.getExtByFormIdAndAttachmentType(wflowFormId,
                AttachmentTypeEnum.ATTACHMENT_TYPE_15.getCode(), null));

        if (extWFlowForm.getPurchaseType() != PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_5.getCode()) {
            purchasePlanNodeAllDataResVO.setSattachments1(sAttachmentService.getExtByFormIdAndAttachmentType(wflowFormId,
                    AttachmentTypeEnum.ATTACHMENT_TYPE_57.getCode(), null));
            purchasePlanNodeAllDataResVO.setSattachments2(sAttachmentService.getExtByFormIdAndAttachmentType(wflowFormId,
                    AttachmentTypeEnum.ATTACHMENT_TYPE_58.getCode(), null));
            purchasePlanNodeAllDataResVO.setSattachments3(sAttachmentService.getExtByFormIdAndAttachmentType(wflowFormId,
                    AttachmentTypeEnum.ATTACHMENT_TYPE_59.getCode(), null));
//			purchasePlanNodeAllDataResVO.setSattachments4(sAttachmentService.getExtByFormIdAndAttachmentType(wflowFormId,
//					AttachmentTypeEnum.ATTACHMENT_TYPE_60.getCode(), null));
        }

        purchasePlanNodeAllDataResVO.setShistoryComments(sHistoryCommentService.findExtByModelTypeAndRelatedId(
                HistoryCommentModelTypeEnum.HistoryCommentModelType7.getCode(), wflowFormId, null));
        return purchasePlanNodeAllDataResVO;
    }

    /**
     * 答疑／补遗节点数据
     *
     * @param formId
     * @return
     */
    @Override
    public AnswerQuestionResponseVO getQuestionAnswerNodeData(String formId) {
        AnswerQuestionResponseVO answerQuestionResponseVO = new AnswerQuestionResponseVO();
        WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(formId);
        answerQuestionResponseVO.setTimeFlag(isTime(wFlowFormTimeNode.getQuestions(), null));
        answerQuestionResponseVO.setAnswerTime(wFlowFormTimeNode.getAnswers());
        answerQuestionResponseVO.setQuestionTime(wFlowFormTimeNode.getQuestions());
        List<QuestionAnswerResVO> result = Lists.newArrayList();
        answerQuestionResponseVO.setQuestionAnswerResVOS(result);
        List<ExtWFlowFormQuestionAnswer> extByFormIdOrderSNum = wFlowFormQuestionAnswerService.getExtByFormIdOrderSNum(formId);
        int snTem = 0;
        QuestionAnswerResVO vo = null;
        for (ExtWFlowFormQuestionAnswer w : extByFormIdOrderSNum) {
            if (w.getSegmentsNumber() != snTem) {
                snTem = w.getSegmentsNumber();
                vo = new QuestionAnswerResVO();
                vo.setSegmentsNumber(snTem);
                vo.setWflowFormQuestionAnswers(Lists.newArrayList());
                result.add(vo);
            }
            vo.getWflowFormQuestionAnswers().add(w);
        }
        return answerQuestionResponseVO;
    }

    /**
     * 回标节点数据
     *
     * @param wflowFormId
     * @return
     */
    @Override
    public BackBidRspVO selectBackBidNodeData(String wflowFormId, Integer round) {
        BackBidRspVO backBidRspVO = new BackBidRspVO();
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(2);
        params.put("formId", wflowFormId);

        WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(wflowFormId);
        if (round == 1) {
            params.put("bright", AttachmentTypeEnum.ATTACHMENT_TYPE_23.getCode());
            params.put("dark", AttachmentTypeEnum.ATTACHMENT_TYPE_24.getCode());
            params.put("business", AttachmentTypeEnum.ATTACHMENT_TYPE_25.getCode());
            params.put("sendBidOrNot", CommonConstants.YES_INTEGER);
            backBidRspVO.setDelayTime(wFlowFormTimeNode.getBackBid());
            backBidRspVO.setExtensionDelayTime(wFlowFormTimeNode.getBackBidDelay());
            backBidRspVO.setTimeFlag(isTime(wFlowFormTimeNode.getBackBid(), wFlowFormTimeNode.getBackBidDelay()));
        } else if (round == 2) {//二轮回标
            params.put("backBidOrNot", CommonConstants.YES_INTEGER);
            params.put("business", AttachmentTypeEnum.ATTACHMENT_TYPE_38.getCode());
            backBidRspVO.setDelayTime(wFlowFormTimeNode.getTwoRoundBackBid());
            backBidRspVO.setExtensionDelayTime(wFlowFormTimeNode.getTwoRoundBackBidDelay());
            backBidRspVO.setTimeFlag(isTime(wFlowFormTimeNode.getTwoRoundBackBid(), wFlowFormTimeNode.getTwoRoundBackBidDelay()));

        } else if (round == 3) {//商务谈判
            WFlowForm wFlowForm = wFlowFormService.selectById(wflowFormId);
            Integer flowType = wFlowForm.getFlowType();
            if (flowType != PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_5.getCode() &&
                    flowType != PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_6.getCode() &&
                    flowType != PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_7.getCode())
                params.put("backBidOrNot", CommonConstants.YES_INTEGER);
            params.put("business", AttachmentTypeEnum.ATTACHMENT_TYPE_39.getCode());
            backBidRspVO.setDelayTime(wFlowFormTimeNode.getBusinessNegoteReturn());
            backBidRspVO.setExtensionDelayTime(wFlowFormTimeNode.getBusinessNegoteReturnDelay());
            backBidRspVO.setTimeFlag(isTime(wFlowFormTimeNode.getBusinessNegoteReturn(), wFlowFormTimeNode.getBusinessNegoteReturnDelay()));
            backBidRspVO.setExtWFlowFormInquiringBids(wFlowFormInquiringBidService.getExtByFormId(wflowFormId));
            backBidRspVO.setSattachments(sAttachmentService.getExtByFormIdAndAttachmentType(wflowFormId,
                    AttachmentTypeEnum.ATTACHMENT_TYPE_44.getCode(), null));

        }
        backBidRspVO.setCalibrationInfoRspVOS(backBidInfoFormat(wFlowFormBackBidService.getExtBackBidByMap(params)));
        return backBidRspVO;
    }

    /**
     * 开标节点数据
     *
     * @param formId
     * @return
     */
    @Override
    public OpenBidRspVO selectOpenBidNodeData(String formId) {
        OpenBidRspVO openBidRspVO = new OpenBidRspVO();
        openBidRspVO.setIsScoreEnd(wFlowFormIbTechScoreService.isSocreEnd(formId));

        Map<String, Object> params = Maps.newHashMapWithExpectedSize(2);
        params.put("formId", formId);
        params.put("backBidOrNot", CommonConstants.YES_INTEGER);
        params.put("bright", AttachmentTypeEnum.ATTACHMENT_TYPE_23.getCode());
        params.put("dark", AttachmentTypeEnum.ATTACHMENT_TYPE_24.getCode());
        params.put("business", AttachmentTypeEnum.ATTACHMENT_TYPE_25.getCode());
        List<ExtWFlowFormBackBid> extWFlowFormBackBids = wFlowFormBackBidService.getExtBackBidByMap(params);
        List<OpenBidInfoVO> openBidInfoVOS = Lists.newArrayList();
        int snTem = 0;
        OpenBidInfoVO vo = null;
        for (ExtWFlowFormBackBid s : extWFlowFormBackBids) {
            if (s.getSegmentsNumber() != snTem) {
                snTem = s.getSegmentsNumber();
                vo = new OpenBidInfoVO(s.getSegmentsNumber());
                vo.setExtWFlowFormBackBids(Lists.newArrayList());
                openBidInfoVOS.add(vo);
            }
            vo.getExtWFlowFormBackBids().add(s);
        }
        openBidRspVO.setOpenBidInfoVOS(openBidInfoVOS);
        openBidRspVO.setAttachments(sAttachmentService.getByFormIdAndAttachmentType(formId, AttachmentTypeEnum.ATTACHMENT_TYPE_26.getCode(), null));
        return openBidRspVO;
    }


    /**
     * 开标统一接口
     *
     * @param formId
     */
    @Override
    public void openBid(String formId) {
        WFlowForm wFlowForm = wFlowFormService.selectById(formId);
        WFlowSubForm wFlowSubForm = wFlowSubFormService.selectByFormId(formId);
        Integer openBidType = wFlowForm.getOpenBidOrders();
        Date date = DateUtils.getNow();

        if (wFlowForm.getFlowFormSubStatus().equals(WorkFlowLineStatusEnum.LINE_STATUS_TWO_BACK_BID.getCode() + "")) {
            wFlowSubForm.setSendBidReturnStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_9_STATUS_3.getCode());
            wFlowSubForm.setSendBidReturnTime(date);
        } else if (wFlowForm.getFlowFormSubStatus().equals(WorkFlowLineStatusEnum.LINE_STATUS_BUSINESS_NEGOTIATION.getCode() + "")) {
            wFlowSubForm.setBusinessNegotiationStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_10_STATUS_3.getCode());
            wFlowSubForm.setBusinessNegotiationTime(date);
        } else {
            if (wFlowSubForm.getTechnicalBidOpenFlag() != CommonConstants.YES_INTEGER) {
                if (openBidType == PurchaseCommonEnum.OPEN_BID_ORDER_1.getCode()) {
                    wFlowSubForm.setTechnicalBidOpenFlag(CommonConstants.YES_INTEGER);
                    wFlowSubForm.setTechnicalBidOpenTime(date);
                    wFlowSubForm.setBusinessBidOpenFlag(CommonConstants.YES_INTEGER);
                    wFlowSubForm.setBusinessBidOpenTime(date);
                } else {
                    wFlowSubForm.setTechnicalBidOpenFlag(CommonConstants.YES_INTEGER);
                    wFlowSubForm.setTechnicalBidOpenTime(date);
                }
            } else {
                wFlowSubForm.setBusinessBidOpenFlag(CommonConstants.YES_INTEGER);
                wFlowSubForm.setBusinessBidOpenTime(date);
            }
        }
        wFlowSubFormService.updateByFormId(wFlowSubForm);

    }

    /**
     * 获取询标节点数据
     *
     * @param flowFormId
     * @return
     */

    @Override
    public InquiringBidRspVO selectInquiringBidNodeData(String flowFormId) {
        InquiringBidRspVO inquiringBidRspVO = new InquiringBidRspVO();
        inquiringBidRspVO.setTime(wFlowFormTimeNodeService.selectByFlowFormId(flowFormId).getInquiringBidDelay());
        inquiringBidRspVO.setExtWFlowFormInquiringBids(wFlowFormInquiringBidService.getExtByFormId(flowFormId));
        boolean nameFalg = true;
        String userIdTem = "";
        InquiringBidInfoVO vo = null;
        List<ExtWFlowFormIbTechScore> extWFlowFormIbTechScores = wFlowFormIbTechScoreService.getExtByFormId(flowFormId);//排序过的数据
        Integer isScoreEnd = 1;
        for (ExtWFlowFormIbTechScore w : extWFlowFormIbTechScores) {
            if (!w.getUserId().equals(userIdTem)) {
                if (!userIdTem.equals("")) {
                    nameFalg = false;
                }
                userIdTem = w.getUserId();
                vo = new InquiringBidInfoVO(w.getUserName());
                inquiringBidRspVO.getScores().getDetails().add(vo);
            }
            if (nameFalg) {
                IdNameVO idNameVO = new IdNameVO(w.getSupplierId(), w.getSupplierName());
                inquiringBidRspVO.getScores().getSuppliers().add(idNameVO);
            }
            vo.getBrightScoreList().add(w.getTechnicalScore());
            vo.getDarkScoreList().add(w.getTechnicalDarkScore());
            vo.getPmScoreList().add(w.getPmInterviewScore());

            Double s1 = w.getTechnicalScore() == null ? 0 : w.getTechnicalScore();
            Double s2 = w.getTechnicalDarkScore() == null ? 0 : w.getTechnicalDarkScore();
            Double s3 = w.getPmInterviewScore() == null ? 0 : w.getPmInterviewScore();
            Double total = s1 + s2 + s3;
            if (total == 0) {
                isScoreEnd = 0;
            }
            vo.getAllScoreList().add(total == 0 ? null : total);
        }
        inquiringBidRspVO.setIsScoreEnd(isScoreEnd);
        int denominator = inquiringBidRspVO.getScores().getDetails().size();
        for (int i = 0; i < inquiringBidRspVO.getScores().getSuppliers().size(); i++) {
            double avg1 = 0, avg2 = 0, avg3 = 0;
            Integer nodenominator = 0;//没有打分的
            for (int j = 0; j < denominator; j++) {
                Double a1 = inquiringBidRspVO.getScores().getDetails().get(j).getBrightScoreList().get(i);
                Double a2 = inquiringBidRspVO.getScores().getDetails().get(j).getDarkScoreList().get(i);
                Double a3 = inquiringBidRspVO.getScores().getDetails().get(j).getPmScoreList().get(i);
                if (a1 == null && a2 == null && a3 == null) {
                    nodenominator++;
                } else {
                    avg1 += (a1 == null ? 0 : a1);
                    avg2 += (a2 == null ? 0 : a2);
                    avg3 += (a3 == null ? 0 : a3);
                }
            }
            if (nodenominator == denominator) {//都没打分
                inquiringBidRspVO.getScores().getBrightWeightScore().add(null);
                inquiringBidRspVO.getScores().getDarkWeightScore().add(null);
                inquiringBidRspVO.getScores().getPmWeightScore().add(null);
                inquiringBidRspVO.getScores().getTotalWeightScore().add(null);

            } else {
                DecimalFormat dFormat = new DecimalFormat("#.00");
                inquiringBidRspVO.getScores().getBrightWeightScore().add(avg1 == 0 ? null : Double.valueOf(dFormat.format(avg1 / denominator)));
                inquiringBidRspVO.getScores().getDarkWeightScore().add(avg2 == 0 ? null : Double.valueOf(dFormat.format(avg2 / denominator)));
                inquiringBidRspVO.getScores().getPmWeightScore().add(avg3 == 0 ? null : Double.valueOf(dFormat.format(avg3 / denominator)));
                inquiringBidRspVO.getScores().getTotalWeightScore().add(Double.valueOf(dFormat.format((avg1 + avg2 + avg3) / denominator)));
            }
        }

        return inquiringBidRspVO;
    }


    /**
     * 附件历史
     *
     * @param wflowFormId
     * @return
     */
    @Override
    public List<SAttachAllResVO> selectAllSAttach(String wflowFormId) {
        List<SAttachAllResVO> sAttachAllResVOS = Lists.newArrayList();
        List<SAttachment> sAttachments = sAttachmentService.getByFormIdOrderByType(wflowFormId);
        int snTem = 0;
        SAttachAllResVO vo = null;
        for (SAttachment s : sAttachments) {
            if (s.getAttachmentType() != snTem) {
                snTem = s.getAttachmentType();
                vo = new SAttachAllResVO();
                vo.setTitle(AttachmentTypeEnum.getNameByKey(snTem));
                vo.setAttachments(Lists.newArrayList());
                sAttachAllResVOS.add(vo);
            }
            vo.getAttachments().add(s);
        }
        return sAttachAllResVOS;
    }

    public void parseExtWFowForm(List<ExtWFlowForm> data) {
        if (data != null)
            for (ExtWFlowForm ew : data) {

//				//采购状态
//				SysDict dictFlowFormStatus = sysDictService.getSysDictByValueAndType(ew.getFlowFormStatus(), DictTypeConstants.PURCHASE_STATUS);
//				if(dictFlowFormStatus != null)
//					ew.setFlowFormStatusName(dictFlowFormStatus.getDictLabel());
//
//
//				//采购方式
//				SysDict dictPurchaseType = sysDictService.getSysDictByValueAndType(ew.getPurchaseType()+"", DictTypeConstants.PURCHASE_FLOW_TYPE);
//				if(dictPurchaseType != null){
//					ew.setPurchaseTypeName(dictPurchaseType.getDictLabel());
//				}

                //当前工作节点/小状态
                if (StringUtils.isNotBlank(ew.getFlowFormSubStatus())) {
                    ew.setFlowFormSubStatusName(this.getFlowFormSubStatusName(ew.getFlowFormSubStatus()));
                }

            }
    }

    /**
     * 获取当前工作节点name
     *
     * @param flowFormSubStatus
     * @return
     */
    private String getFlowFormSubStatusName(String flowFormSubStatus) {
        if (StringUtils.isBlank(flowFormSubStatus)) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        List<String> statusList = new ArrayList<>();
        for (String status : flowFormSubStatus.split(",")) {
            statusList.add(status);
        }

        if (statusList != null && statusList.size() > 0) {
            for (int i = 0; i < statusList.size(); i++) {
                SysDict dictPurchaseType = sysDictService.getSysDictByValueAndType(statusList.get(i), DictTypeConstants.PURCHASE_FLOW_SUB_TYPE);
                if (dictPurchaseType != null) {
                    if (sb.length() > 0) {
                        sb.append("," + dictPurchaseType.getDictLabel());
                    } else {
                        sb.append(dictPurchaseType.getDictLabel());
                    }
                }

            }
        }
        return sb.toString();
    }

    /**
     * 保存采购方案
     *
     * @param purchasePlanRequestVO
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public RestReturnResult savePurchasePlan(PurchasePlanRequestVO purchasePlanRequestVO) {
        RestReturnResult<Object> restResult = new RestReturnResult<Object>(CommonConstants.FAIL, purchasePlanRequestVO, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);
        try {
            WFlowFormRequestVO wFlowFormRequestVO = purchasePlanRequestVO.getWflowFormRequestVO();
            WFlowForm wFlowForm = new WFlowForm();
            BeanUtils.copyProperties(wFlowFormRequestVO, wFlowForm);
            wFlowForm.setBaseFeilds("SYSTEM", null, 0, true);
            boolean result = wFlowFormService.insert(wFlowForm);
            if (result) {
                throw new RuntimeException("保存数据失败", new ServiceThrowable());
            }

            WFlowFormTimeNodeRequestVO wFlowFormTimeNodeRequestVO = purchasePlanRequestVO.getWflowFormTimeNodeRequestVO();
            WFlowFormTimeNode wFlowFormTimeNode = new WFlowFormTimeNode();
            BeanUtils.copyProperties(wFlowFormTimeNodeRequestVO, wFlowFormTimeNode);
            wFlowFormTimeNode.setBaseFeilds("SYSTEM", null, 0, true);
            wFlowFormTimeNode.setFlowFormId(wFlowForm.getId());
            result = wFlowFormTimeNodeService.insert(wFlowFormTimeNode);
            if (result) {
                throw new RuntimeException("保存数据失败", new ServiceThrowable());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
        return restResult;
    }


    /***
     * 启动采购
     * @param vo
     * @return
     */

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void generateFlowForm(PurchaseFlowFormBisReqVO vo) {
        String handelUser = null;
        try {

            WFlowForm wflowForm = new WFlowForm();
            wflowForm.setBaseFeilds(UserUtils.getCurrentUserId(), "",
                    CommonConstants.DEL_FLAG_NORMAL, true);
            if (vo.getPurchasePlanType() == PurchaseCommonEnum.PURCHASE_PLAN_TYPE_SPECIAL.getCode()) {
                PSpecialPurchasePlan pspplan = pSpecialPurchasePlanService.selectById(vo.getPurchasePlanId());
                handelUser = pspplan.getHandleUser();
                if (pspplan.getPlanStatus() != PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_3.getCode()) {
                    throw new RuntimeException("不是确认状态", new ServiceThrowable());
                }
//				PContactPlan pcplan = null;
//				if(StringUtils.isEmpty(pspplan.getContactPlanId()))
//					pcplan = new PContactPlan();
//				else
//					pcplan = pContactPlanService.selectById(pspplan.getContactPlanId());

                wflowForm.setHandleUser(pspplan.getHandleUser());
                wflowForm.setPurchasePlanType(vo.getPurchasePlanType());
                wflowForm.setPurchasePlanId(pspplan.getId());
                wflowForm.setFlowType(pspplan.getPurchaseType());
                wflowForm.setFlowCode(DateUtils.getNowString());
                wflowForm.setFlowFormStatus(WFlowFormStatusEnum.WFLOW_FROM_STATUS_1.getCode() + "");//进行中
                wflowForm.setFlowFormSubStatus(WorkFlowLineStatusEnum.LINE_STATUS_PURCHASE_SCHEME.getCode() + "");//采购方案
                wflowForm.setResponsibilityId(pspplan.getRegionalCompanyId());
                wflowForm.setRegionalCompanyId(pspplan.getRegionalCompanyId());
                wflowForm.setOriginatorUser(pspplan.getOriginatorUser());//发包人
                wflowForm.setProjectId(pspplan.getProjectId());
                wflowForm.setContractId(pspplan.getContractId());
                wflowForm.setContractName(pspplan.getContractName());
                wflowForm.setContractCode(pspplan.getContractCode());
                wflowForm.setProjectByStage(pspplan.getProjectByStage());
                wflowForm.setPurchaseItemName(pspplan.getPurchaseItemName());
                wflowForm.setProcuringEntity(pspplan.getProcuringEntity());//采购主体
                wflowForm.setSegmentsNumber(pspplan.getSegmentsNumber());//标段数量
                wflowForm.setPurchaseType(pspplan.getPurchaseType());
                wflowForm.setPurchaseClassification(pspplan.getPurchaseClassification());//采购分类
                wflowForm.setMbsBpmFlag(WFlowFormStatusEnum.MBS_BPM_FLAG_1.getCode());
                wflowForm.setPlanBudgetPrices(pspplan.getPlanBudgetPrices());
                wflowForm.setPlanBudgetTime(pspplan.getPlanBudgetTime());

                PSpecialPurchasePlan pspp = pSpecialPurchasePlanService.getSpecialPurchasePlanById(pspplan.getId());
                pspp.setId(pspplan.getId());
                pspp.setPlanStatus(PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_4.getCode());
                pspp.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);

                pSpecialPurchasePlanService.updateById(pspp);
            } else {//战略
                PStrategicPurchaseContact pStrategicPurchaseContact = pStrategicPurchaseContactService.selectById(vo.getPurchasePlanId());

                handelUser = vo.getHandelUser() != null ? vo.getHandelUser() : UserUtils.getCurrentUserId();

                wflowForm.setHandleUser(handelUser);
                wflowForm.setPurchasePlanType(vo.getPurchasePlanType());
                wflowForm.setPurchasePlanId(pStrategicPurchaseContact.getId());
                wflowForm.setFlowType(vo.getFlowType());
                wflowForm.setSegmentsNumber(1);
                wflowForm.setFlowCode(DateUtils.getNowString());
                wflowForm.setFlowFormStatus(WFlowFormStatusEnum.WFLOW_FROM_STATUS_1.getCode() + "");//进行中
                wflowForm.setFlowFormSubStatus(WorkFlowLineStatusEnum.LINE_STATUS_PURCHASE_SCHEME.getCode() + "");//采购方案
                wflowForm.setResponsibilityId(pStrategicPurchaseContact.getResponsibilityId());
                wflowForm.setRegionalCompanyId(pStrategicPurchaseContact.getRegionalCompanyId());

                wflowForm.setContractId(pStrategicPurchaseContact.getContractId());
                wflowForm.setContractName(pStrategicPurchaseContact.getContractName());
                wflowForm.setContractCode(pStrategicPurchaseContact.getContractCode());

//                wflowForm.setProjectId(pSpOverallPlanDetail.getProjectId());
//                wflowForm.setProjectByStage(pspplan.getProjectByStage());
//                wflowForm.setProjectLocation();
                wflowForm.setPurchaseItemName(vo.getPurchaseItemName());
                if (vo.getFlowType() == null)
                    wflowForm.setPurchaseType(pStrategicPurchaseContact.getPurchaseType());
                else {
                    wflowForm.setPurchaseType(vo.getFlowType());
                    pStrategicPurchaseContact.setPurchaseType(vo.getFlowType());
                }
                wflowForm.setPurchaseCategoryId(pStrategicPurchaseContact.getPurchaseCategoryId());
                wflowForm.setMbsBpmFlag(WFlowFormStatusEnum.MBS_BPM_FLAG_1.getCode());
                wflowForm.setPurchasedAmount(pStrategicPurchaseContact.getEngineeringAmount());
//                wflowForm.setPurchaseChannels(pSpOverallPlanDetail.get());
//                wflowForm.setStartConstructionTime(pSpOverallPlanDetail.get());
//                wflowForm.setEndConstructionTime(pSpOverallPlanDetail.getPlanFinishedTime());
//                wflowForm.setSignedYears(pSpOverallPlanDetail.getPlanSignedYears());

                pStrategicPurchaseContact.setPurchaseItemName(vo.getPurchaseItemName());
                if (vo.getFlowType() != null) {
                    pStrategicPurchaseContact.setPurchaseType(vo.getFlowType());
                }
                pStrategicPurchaseContact.setHandleUser(handelUser);
                pStrategicPurchaseContact.setPurchaseItemStatus(PurchaseCommonEnum.P_OVER_PLAN_STATUS_4.getCode());
                pStrategicPurchaseContactService.updateById(pStrategicPurchaseContact);
            }
            //个节点状态
            WFlowSubForm wFlowSubForm = new WFlowSubForm();
            wFlowSubForm.setFlowFormId(wflowForm.getId());
            wFlowSubForm.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
            wFlowSubFormService.insert(wFlowSubForm);

            AProcessConfig aProcessConfig = aProcessConfigService.
                    getAProcessConfigByProcessTypeAndDelopTime(wflowForm.getFlowType());
            wflowForm.setProcessConfigId(aProcessConfig.getId());
            if (aProcessConfig != null && StringUtils.isNotEmpty(aProcessConfig.getProcessKey())) {
                if (aProcessConfig.getDeployTime() != null) {
                    Map<String, Object> variables = new HashMap<>(1);
                    variables.put("flowFormId", wflowForm.getId());
                    ProcessInstance processInstance = activitiRuntimeService.startProcessInstanceByKey(aProcessConfig.getProcessKey(), variables);
                    saveWorkOrderCommonMethod(wflowForm, handelUser, processInstance, null);//生成采购列表

                    //sHistoryCommentService.insert(buildGenerateFlowConfirmHistory(vo.getPurchasePlanId()));
                } else {
                    throw new RuntimeException("流程配置未部署", new ServiceThrowable());
                }
            } else {
                throw new RuntimeException("流程配置不存在", new ServiceThrowable());
            }

            //通知招标项状态
            SynSourcingDataVo synSourcingDataVo = new SynSourcingDataVo();
            synSourcingDataVo.setSrId(wflowForm.getContractId());
            synSourcingDataVo.setSrStatus("1");
            synSourcingDataVo.setSrPurchaseType(PurchasePlanFlowTypeEnum.getSynCodeByKey(wflowForm.getPurchaseType()) + "");
//            synDataService.changeSourcingStatus(synSourcingDataVo);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        } finally {
            //很重要
            ThreadLocalWFlowFormSteps.getInstance().remove();
        }
    }


    SMyDeals buildCommonDeals(String relateId, String subRelateId, int subType, int actionType, String sCommentConfig,
                              String handelUser, Date endTime, String flowTaskId) {
        SMyDeals planConfirmDeal = new SMyDeals();
        planConfirmDeal.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
        planConfirmDeal.setDealType(DealTypeEnum.PURCHASE.getCode());
        planConfirmDeal.setDealSubType(subType);
        planConfirmDeal.setActionType(actionType);
        planConfirmDeal.setFlowTaskId(flowTaskId);
        planConfirmDeal.setRelatedId(relateId);
        planConfirmDeal.setSubRelatedId(subRelateId);
        planConfirmDeal.setUserId(handelUser);
        planConfirmDeal.setDealTitle(sCommentConfig);
        planConfirmDeal.setDealEndTime(endTime);
        planConfirmDeal.setDoneFlag(CommonConstants.DEL_FLAG_NORMAL);

        return planConfirmDeal;
    }


    /**
     * 提交采购方案
     *
     * @param purchasePlanParam
     * @return RestReturnResult
     */

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void submitPurchasePlan(PurchasePlanParam purchasePlanParam) {
        try {
            WFlowForm wfvo = purchasePlanParam.getWFlowForm();
            WFlowSubForm wsf = wFlowSubFormService.selectByFormId(wfvo.getId());
            if (purchasePlanParam.getType() == PurchaseCommonEnum.PURCHASE_PLAN_SUBMIT.getCode() &&
                    wsf.getPurchaseSolutionStatus() >= PurchaseNodeButtonStatusEnum.PURCHASE_NODE_1_STATUS_2.getCode()) {
                throw new RuntimeException("不允许重复发起审批！！！", new ServiceThrowable());
            }

            WFlowForm wf = wFlowFormService.selectById(wfvo.getId());
            BeanUtils.copyProperties(wfvo, wf);
            wf.setUpdateBy(UserUtils.getCurrentUserId());
            wf.setUpdateDate(DateUtils.getNow());
            wFlowFormService.updateAllColumnById(wf);
            WFlowFormTimeNode wFlowFormTimeNodeVo = purchasePlanParam.getWFlowFormTimeNode();
            WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeVo;
            if (StringUtils.isNotEmpty(wFlowFormTimeNodeVo.getId())) {
                wFlowFormTimeNode = wlowFormTimeNodeService.selectById(wFlowFormTimeNodeVo.getId());
                BeanUtils.copyProperties(wFlowFormTimeNodeVo, wFlowFormTimeNode);
                wFlowFormTimeNode.setUpdateBy(UserUtils.getCurrentUserId());
                wFlowFormTimeNode.setUpdateDate(DateUtils.getNow());
            } else {
                wFlowFormTimeNode.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                wFlowFormTimeNodeVo.setFlowFormId(wfvo.getId());
            }
            wFlowFormTimeNode.setAnswers(wFlowFormTimeNode.getInitAnswers());
            wFlowFormTimeNode.setQuestions(wFlowFormTimeNode.getInitQuestions());
            wFlowFormTimeNode.setBackBid(wFlowFormTimeNode.getInitBackBid());

            wFlowFormTimeNode.setBusinessNegoteReturn(wFlowFormTimeNode.getInitBusinessNegoteReturn());
            wFlowFormTimeNode.setTwoRoundBackBid(wFlowFormTimeNode.getInitTwoRoundBackBid());
            //wFlowFormTimeNode.setBidEvaluation(wFlowFormTimeNode.getInitBidEvaluation());
            wlowFormTimeNodeService.insertOrUpdate(wFlowFormTimeNode);

            if (purchasePlanParam.getType() == PurchaseCommonEnum.PURCHASE_PLAN_SUBMIT.getCode()) {//提交
                //sendBpm(wfvo.getId(),wfvo.getId(),AbutmentSubTypeEnum.LINE_STATUS_PURCHASE_SCHEME.getCode());

                Map<String, Object> result = sendBpmSolutionDoc(wf);
                String workflowUrl = String.valueOf(result.get("BPM_URL"));
                String nodeName = sCommentConfigService.getValueByCode(CommentConfigEnum.P_PLAN_NODE_NAME_HISTORY_LAUNCH.getCode());
                SHistoryComment historyComment = buildCommonHistory(wf.getId(), wf.getId(),
                        HistoryCommentModelTypeEnum.HistoryCommentModelType7.getCode(), "",
                        PurchaseActionNameEnum.PURCHASE_PLAN_2_1.getDesc(), nodeName, 0, false);
                historyComment.setCommentUrl(workflowUrl);
                sHistoryCommentService.saveSHistoryComment(historyComment);
                updateWfformMbsStatus(wf.getId(), WFlowFormStatusEnum.MBS_BPM_FLAG_2.getCode());

                WFlowSubForm wFlowSubForm = new WFlowSubForm();
                wFlowSubForm.setFlowFormId(wf.getId());
                wFlowSubForm.setPurchaseSolutionStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_1_STATUS_2.getCode());
                wFlowSubForm.setPurchaseSolutionActionTime(DateUtils.getNow());
                wFlowSubFormService.updateByFormId(wFlowSubForm);

                //发送招标文件代办
                SMyDeals where = new SMyDeals();
                where.setRelatedId(wf.getId());
                where.setActionType(MyDealActionTypeEnum.BIDDING_DOCUMENTS.getCode());
                where.setDoneFlag(CommonConstants.UNDONG_FLAG);
                where.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
                SMyDeals docuSmyDeal = sMyDealsService.selectOneByEntity(where);
                if (docuSmyDeal == null) {
                    Map<String, Object> param = Maps.newHashMapWithExpectedSize(3);
                    param.put("flowFormId", wf.getId());
                    param.put("doneFlag", CommonConstants.UNDONG_FLAG);
                    param.put("lineStatus", 3);
                    List<WFlowFormSteps> currsets = wFlowFormStepsService.getWFlowFormStepsByCnd(param);
                    if (CollectionUtils.isNotEmpty(currsets)) {

                        SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_LINE_STATUS_BID_DOC_DEAL.getCode());
                        SysDict sysDict = sysDictService.getSysDictByLabelAndType("3", CommonConstants.SYS_DICT_TYPE_PURCHASE_STATUS_MAP);
                        sMyDealsService.insert(buildCommonDeals(wf.getId(), wf.getId(),
                                MyDealSubTypeEnum.BIDDING_DOCUMENTS.getCode(),
                                MyDealActionTypeEnum.BIDDING_DOCUMENTS.getCode(),
                                MessageFormat.format(sc.getConfigValue(), wf.getPurchaseItemName(), sysDict.getDictDescription()),
                                wf.getHandleUser(), null, currsets.get(0).getTaskId()));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());

        }
    }

    /**
     * 采购方案bpm
     *
     * @param wFlowForm
     */
    private Map<String, Object> sendBpmSolutionDoc(WFlowForm wFlowForm) {
        String nowString = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        FlowFormDataVo flowFormDataVo = new FlowFormDataVo();
        flowFormDataVo.setScSrId(wFlowForm.getContractId());
        flowFormDataVo.setScCreateDate(nowString);
        flowFormDataVo.setScExeAppDate(nowString);
        flowFormDataVo.setScExeAppName(UserUtils.getCurrentUserVo().getRealName());
//        flowFormDataVo.setScExeAppRem("");
        flowFormDataVo.setScCreateUserName(wFlowForm.getHandleUser());
        flowFormDataVo.setSourcingCandidateItems(Lists.newArrayList());
        flowFormDataVo.setScServiceUuid(wFlowForm.getId());
        flowFormDataVo.setScPurchasingScope(wFlowForm.getPurchaseRange());
        flowFormDataVo.setScSectionDivision(wFlowForm.getSegmentsSplits());

        if (wFlowForm.getContractValuationMethod() != null) {
            SysDict dictContractValuationMethod = sysDictService.getSysDictByValueAndType(wFlowForm.getContractValuationMethod() + "", DictTypeConstants.SYS_DICT_TYPE_CONTRACT_VALUATION_METHOD_TYPE_MAP);
            if (dictContractValuationMethod != null) {
                flowFormDataVo.setScContractValuation(dictContractValuationMethod.getDictLabel());
            }
        }

        if (wFlowForm.getCalibrationPrinciple() != null) {
            SysDict dictCalibrationPrinciple = sysDictService.getSysDictByValueAndType(wFlowForm.getCalibrationPrinciple() + "", DictTypeConstants.SYS_DICT_TYPE_CALIBRATION_PRINCIPLE_TYPE_MAP);
            if (dictCalibrationPrinciple != null) {
                flowFormDataVo.setScAlingPrinciple(dictCalibrationPrinciple.getDictLabel());
            }
        }

        if (wFlowForm.getBackBidRounds() != null) {
            SysDict dictBackBidRounds = sysDictService.getSysDictByValueAndType(wFlowForm.getBackBidRounds() + "", DictTypeConstants.SYS_DICT_TYPE_BACK_BID_ROUNDS_TYPE_MAP);
            if (dictBackBidRounds != null) {
                flowFormDataVo.setScBackStandard(dictBackBidRounds.getDictLabel());
            }
        }

        if (wFlowForm.getPurchaseType() != null) {
            SysDict dictPurchaseType = sysDictService.getSysDictByValueAndType(wFlowForm.getPurchaseType() + "", DictTypeConstants.SYS_DICT_TYPE_PURCHASE_TYPE_MAP);
            if (dictPurchaseType != null) {
                flowFormDataVo.setScPurchasingMethod(dictPurchaseType.getDictLabel());
            }
        }

        if (wFlowForm.getCalibrationMeetingOrNot() != null) {
            SysDict dictCalibrationMeetingOrNot = sysDictService.getSysDictByValueAndType(wFlowForm.getCalibrationMeetingOrNot() + "", DictTypeConstants.SYS_DICT_TYPE_TO_CALIBRATE_MAP);
            if (dictCalibrationMeetingOrNot != null) {
                flowFormDataVo.setScYesOrNoDingBiao(dictCalibrationMeetingOrNot.getDictLabel());
            }
        }

        flowFormDataVo.setScDesignSealing(wFlowForm.getDesignSeal() == null ? "" : String.valueOf(wFlowForm.getDesignSeal()));


        if (wFlowForm.getBidSendSampleOrNot() != null) {
            SysDict dictBidSendSampleOrNot = sysDictService.getSysDictByValueAndType(wFlowForm.getBidSendSampleOrNot() + "", DictTypeConstants.SYS_DICT_TYPE_BID_SEND_SAMPLE_MODEL_TYPE_MAP);
            if (dictBidSendSampleOrNot != null) {
                flowFormDataVo.setScSampledelivery(dictBidSendSampleOrNot.getDictLabel());
            }
        }
        flowFormDataVo.setScSupplierConditions(wFlowForm.getEntryConditions() == null ? "" : String.valueOf(wFlowForm.getEntryConditions()));

        WFlowFormBidCandidateUnit where = new WFlowFormBidCandidateUnit();
        where.setFlowFormId(wFlowForm.getId());
        where.setDelFlag(CommonConstants.NO_INTEGER);
        List<ExtWFlowFormBidCandidateUnit> wFlowFormBidCandidateUnits = wFlowFormBidCandidateUnitService.getExtFormList(where);
        for (ExtWFlowFormBidCandidateUnit wFlowFormBidCandidateUnit : wFlowFormBidCandidateUnits) {
            FlowSourcingCandidateDataVo flowSourcingCandidateDataVo = new FlowSourcingCandidateDataVo();
            flowSourcingCandidateDataVo.setSiScServiceUuid(wFlowForm.getId());
            flowSourcingCandidateDataVo.setSiSpId(wFlowFormBidCandidateUnit.getSuppliersId());
            flowSourcingCandidateDataVo.setSiSpName(wFlowFormBidCandidateUnit.getSuppliersName());
            flowSourcingCandidateDataVo.setSiCert(wFlowFormBidCandidateUnit.getQualificationGradeName());
            flowSourcingCandidateDataVo.setSiBrand(wFlowFormBidCandidateUnit.getQualificationGradeName());
            //		flowSourcingCandidateDataVo.setSiInternalAchieve("");
            //		flowSourcingCandidateDataVo.setSiExternalAchieve("");
            flowSourcingCandidateDataVo.setSiSpLevel(String.valueOf(wFlowFormBidCandidateUnit.getSuppliersRank()));
            //		flowSourcingCandidateDataVo.setSiSmName("");
            //		flowSourcingCandidateDataVo.setSiSmLevel("");
            //		flowSourcingCandidateDataVo.setSiSmCertNo("");
            //		flowSourcingCandidateDataVo.setSiSpScore("");
            flowSourcingCandidateDataVo.setSiServiceUuid(wFlowFormBidCandidateUnit.getId());
            flowSourcingCandidateDataVo.setSiSupplierCormForm(wFlowFormBidCandidateUnit.getSupplierSourceInfo());

            if (wFlowFormBidCandidateUnit.getManagementModel() != null) {
                SysDict dictManagementModel = sysDictService.getSysDictByValueAndType(wFlowFormBidCandidateUnit.getManagementModel() + "", DictTypeConstants.MANAGEMENT_MODEL_TYPE);
                if (dictManagementModel != null) {
                    flowSourcingCandidateDataVo.setSiBusinessModel(dictManagementModel.getDictLabel());
                }
            }
            flowFormDataVo.getSourcingCandidateItems().add(flowSourcingCandidateDataVo);
        }

        List<WFlowFormPurchaseTeam> wFlowFormPurchaseTeams = wFlowFormPurchaseTeamService.getTeamByFlowFormId(wFlowForm.getId());
        FlowSourcingHandlerDataVo flowSourcingHandlerDataVo = new FlowSourcingHandlerDataVo();
        flowSourcingHandlerDataVo.setShSrId(wFlowForm.getContractId());
//        flowSourcingHandlerDataVo.setShHandler("");
        flowSourcingHandlerDataVo.setShExeUserName(UserUtils.getCurrentUserVo().getRealName());
        flowSourcingHandlerDataVo.setShExeRealName(UserUtils.getCurrentUserId());
//        flowSourcingHandlerDataVo.setShChargeUserName("");
//        flowSourcingHandlerDataVo.setShChargeRealName("");
//        flowSourcingHandlerDataVo.setShConsultor("");
//        flowSourcingHandlerDataVo.setShAppDate("");
//        flowSourcingHandlerDataVo.setShAppName("");
//        flowSourcingHandlerDataVo.setShAppRem("");
//        flowSourcingHandlerDataVo.setShReviewDate("");
//        flowSourcingHandlerDataVo.setShReviewName("");
//        flowSourcingHandlerDataVo.setShReviewRem("");
//        flowSourcingHandlerDataVo.setShStatus("");
//        flowSourcingHandlerDataVo.setShCostUserName("");
        String econUserName = "";
        String econRealName = "";
        String techUserName = "";
        String techRealName = "";
        for (WFlowFormPurchaseTeam wFlowFormPurchaseTeam : wFlowFormPurchaseTeams) {
            if (wFlowFormPurchaseTeam.getPurchaseJob() == PurchaseCommonEnum.PURCHASE_JOB_1.getCode()) {
                flowSourcingHandlerDataVo.setShAccountUserName(wFlowFormPurchaseTeam.getUserName());
                flowSourcingHandlerDataVo.setShAccountRealName(wFlowFormPurchaseTeam.getUserId());
                econUserName += "," + wFlowFormPurchaseTeam.getUserName();
                econRealName += "," + wFlowFormPurchaseTeam.getUserId();

            } else if (wFlowFormPurchaseTeam.getPurchaseJob() == PurchaseCommonEnum.PURCHASE_JOB_3.getCode()) {
                flowSourcingHandlerDataVo.setShCtrlUserName(wFlowFormPurchaseTeam.getUserName());
                flowSourcingHandlerDataVo.setShCtrlRealName(wFlowFormPurchaseTeam.getUserId());
                techUserName += "," + wFlowFormPurchaseTeam.getUserName();
                techRealName += "," + wFlowFormPurchaseTeam.getUserId();
            } else if (wFlowFormPurchaseTeam.getPurchaseJob() == PurchaseCommonEnum.PURCHASE_JOB_2.getCode()) {
                econUserName += "," + wFlowFormPurchaseTeam.getUserName();
                econRealName += "," + wFlowFormPurchaseTeam.getUserId();
            } else if (wFlowFormPurchaseTeam.getPurchaseJob() == PurchaseCommonEnum.PURCHASE_JOB_4.getCode()) {
                techUserName += "," + wFlowFormPurchaseTeam.getUserName();
                techRealName += "," + wFlowFormPurchaseTeam.getUserId();
            }
        }
        if (StringUtils.isNotEmpty(econUserName))
            econUserName = econUserName.substring(1);
        flowSourcingHandlerDataVo.setShEconUserName(econUserName);
        if (StringUtils.isNotEmpty(econRealName))
            econRealName = econRealName.substring(1);
        flowSourcingHandlerDataVo.setShEconRealName(econRealName);
        if (StringUtils.isNotEmpty(techUserName))
            techUserName = techUserName.substring(1);
        flowSourcingHandlerDataVo.setShTechUserName(techUserName);
        if (StringUtils.isNotEmpty(techRealName))
            techRealName = techRealName.substring(1);
        flowSourcingHandlerDataVo.setShTechRealName(techRealName);
        flowFormDataVo.setSourcingHandler(flowSourcingHandlerDataVo);
        return bpmUtil.invokePurchaseSolutionDoc(flowFormDataVo);
    }

    private Map<String, Object> sendBpmBidDoc(WFlowForm wFlowForm) {
        FlowFormDataVo flowFormDataVo = new FlowFormDataVo();
        flowFormDataVo.setSfSrId(wFlowForm.getContractId());
        flowFormDataVo.setSfStartUserName(UserUtils.getCurrentUserId());
        flowFormDataVo.setSfStartRealName(UserUtils.getCurrentUserVo().getRealName());
        flowFormDataVo.setSfServiceUuid(wFlowForm.getId());
        flowFormDataVo.setSrRem(wFlowForm.getPurchaseRange());
        flowFormDataVo.setSfGuaranteePeriod(wFlowForm.getWarrantyPeriod());
        if (wFlowForm.getStartConstructionTime() != null)
            flowFormDataVo.setSrStartDate(DateUtils.formatDate(wFlowForm.getStartConstructionTime(), DateUtils.DATE_TIME));
        if (wFlowForm.getEndConstructionTime() != null)
            flowFormDataVo.setSrEndDate(DateUtils.formatDate(wFlowForm.getEndConstructionTime(), DateUtils.DATE_TIME));
        flowFormDataVo.setSfPayType(Encodes.encodeBase64(wFlowForm.getPaymentType()));
        return bpmUtil.invokeApprovalBidDoc(flowFormDataVo);
    }

    private Map<String, Object> sendBpmCalibrationBid(WFlowForm wFlowForm) {
        List<FlowSourcingDecisionDataVo> lstSourcingDecisionItems = new ArrayList<FlowSourcingDecisionDataVo>();
        FlowFormDataVo flowFormDataVo = new FlowFormDataVo();
        flowFormDataVo.setSdSrid(wFlowForm.getContractId());
//		flowFormDataVo.setSdCcType("");
        String cName = "";
        try {
            cName = sysUserService.selectById(wFlowForm.getCreateBy()).getName();
        } catch (Exception e) {
        }
        flowFormDataVo.setSdCreateRealName(cName);
        flowFormDataVo.setSdCreateUserName(wFlowForm.getHandleUser());//wFlowForm.getCreateBy()
        flowFormDataVo.setSdServiceUuid(wFlowForm.getId());
        flowFormDataVo.setSourcingDecisionItems(Lists.newArrayList());

        Map<String, WFlowFormBidCandidateUnit> map = Maps.newHashMap();
        List<WFlowFormBidCandidateUnit> wlowFormBidCandidateUnits = wFlowFormBidCandidateUnitService.getByFormId(wFlowForm.getId());
        for (WFlowFormBidCandidateUnit wFlowFormBidCandidateUnit : wlowFormBidCandidateUnits) {
            map.put(wFlowFormBidCandidateUnit.getSuppliersId(), wFlowFormBidCandidateUnit);
        }
        List<ExtWFlowFormBackBid> extWFlowFormBackBids = wFlowFormBackBidService.getExtBackBidByFormId(wFlowForm.getId());
        for (ExtWFlowFormBackBid extWFlowFormBackBid : extWFlowFormBackBids) {
            String qualificationNames = sSupplierQualificationGradeService.getQualificationNameById(map.get(extWFlowFormBackBid.getSupplierId()).getQualificationGrade());

            FlowSourcingDecisionDataVo flowSourcingDecisionDataVo = new FlowSourcingDecisionDataVo();
            flowSourcingDecisionDataVo.setSdiSdId(wFlowForm.getId());
            flowSourcingDecisionDataVo.setSdiSpId(extWFlowFormBackBid.getSupplierId());
            flowSourcingDecisionDataVo.setSdiSpName(extWFlowFormBackBid.getSupplierName());
            flowSourcingDecisionDataVo.setSdiCert(qualificationNames);
            flowSourcingDecisionDataVo.setSdiBrand(qualificationNames);
            Double finalInterviewInputTax = extWFlowFormBackBid.getCalibrationFinalInputTax();
            Double finalInterviewWithTax = extWFlowFormBackBid.getCalibrationFinalTax();
            if (finalInterviewInputTax == null) {
                finalInterviewInputTax = extWFlowFormBackBid.getFinalInterviewInputTax();
                finalInterviewWithTax = extWFlowFormBackBid.getFinalInterviewWithTax();
            }
            if (finalInterviewInputTax == null) {
                finalInterviewInputTax = extWFlowFormBackBid.getBusinessNegotiationInputTax();
                finalInterviewWithTax = extWFlowFormBackBid.getBusinessNegotiationWithTax();
            }
            if (finalInterviewInputTax == null) {
                finalInterviewInputTax = extWFlowFormBackBid.getRoundTwoInputTax();
                finalInterviewWithTax = extWFlowFormBackBid.getRoundTwoWithTax();
            }
            if (finalInterviewInputTax == null) {
                finalInterviewInputTax = extWFlowFormBackBid.getRoundOneInputTax();
                finalInterviewWithTax = extWFlowFormBackBid.getRoundOneWithTax();
            }
            if (finalInterviewInputTax == null) {
                finalInterviewInputTax = 0d;
                finalInterviewWithTax = 0d;
            }


            flowSourcingDecisionDataVo.setSdiTotalValue(StringUtils.getFormatDouble(finalInterviewInputTax, "0.00"));
            flowSourcingDecisionDataVo.setSdiSegmentDesc(extWFlowFormBackBid.getSegmentsNumber() + "");
            flowSourcingDecisionDataVo.setSdiSegmentValue(StringUtils.getFormatDouble(finalInterviewWithTax, "0.00"));
            //		flowSourcingDecisionDataVo.setSdiRank("");
            flowSourcingDecisionDataVo.setSdiNominated(NumberUtils.toInteger(extWFlowFormBackBid.getAwardBidOrNot()) == CommonConstants.YES_INTEGER ? "Y" : "N");
            String huibiaoStatus = "";
            if (NumberUtils.toInteger(extWFlowFormBackBid.getAwardBidOrNot()) == CommonConstants.YES_INTEGER) {
                huibiaoStatus = "评标约谈";
            } else if (NumberUtils.toInteger(extWFlowFormBackBid.getBidEvaluationFlag()) == CommonConstants.YES_INTEGER) {
                huibiaoStatus = "回标";//"评标约谈";
            } else if (NumberUtils.toInteger(extWFlowFormBackBid.getBusinessNegotiationOrNot()) == CommonConstants.YES_INTEGER) {
                huibiaoStatus = "回标";//"商务谈判";
            } else if (NumberUtils.toInteger(extWFlowFormBackBid.getRoundTwoBackBidOrNot()) == CommonConstants.YES_INTEGER) {
                huibiaoStatus = "回标";//"二轮回标";
            } else if (NumberUtils.toInteger(extWFlowFormBackBid.getBackBidOrNot()) == CommonConstants.YES_INTEGER) {
                huibiaoStatus = "回标";//"回标";
            } else {
                huibiaoStatus = "回标";//"定标";
            }
            flowSourcingDecisionDataVo.setSdiHuiBiaoStatus(huibiaoStatus);

            flowSourcingDecisionDataVo.setSdiServiceUuid(map.get(extWFlowFormBackBid.getSupplierId()).getId());
            lstSourcingDecisionItems.add(flowSourcingDecisionDataVo);
        }

        ///按标段分类
        Map<String, List<FlowSourcingDecisionDataVo>> mapFlowSourcingDecisionDataVos = new HashMap<String, List<FlowSourcingDecisionDataVo>>();
        if (CollectionUtils.isNotEmpty(lstSourcingDecisionItems)) {
            for (FlowSourcingDecisionDataVo item : lstSourcingDecisionItems) {
                List<FlowSourcingDecisionDataVo> lstValues = mapFlowSourcingDecisionDataVos.get(item.getSdiSegmentDesc());
                if (CollectionUtils.isEmpty(lstValues)) {
                    lstValues = new ArrayList<FlowSourcingDecisionDataVo>();
                }
                lstValues.add(item);
                mapFlowSourcingDecisionDataVos.put(item.getSdiSegmentDesc(), lstValues);
            }
        }

        ///排序及构建
        List<FlowSourcingDecisionDataVo> lstSortedSourcingDecisionItems = new ArrayList<FlowSourcingDecisionDataVo>();
        for (Map.Entry<String, List<FlowSourcingDecisionDataVo>> entry : mapFlowSourcingDecisionDataVos.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            List<FlowSourcingDecisionDataVo> lstValues = entry.getValue();
            int rankNum = 1;
            if (CollectionUtils.isNotEmpty(lstValues)) {
                Collections.sort(lstValues);
                for (int i = 0; i < lstValues.size(); i++) {
                    FlowSourcingDecisionDataVo item = lstValues.get(i);
                    if (NumberUtils.toDouble(item.getSdiSegmentValue()) == 0d) {
                        item.setSdiHuiBiaoStatus("弃标");
                    } else {
                        item.setSdiRank(rankNum + "");
                        rankNum++;
                    }
                    lstSortedSourcingDecisionItems.add(item);
                }
            }
        }

        flowFormDataVo.setSourcingDecisionItems(lstSortedSourcingDecisionItems);
        return bpmUtil.invokeApprovalCalibrationBid(flowFormDataVo);
    }

    public void updateWfformMbsStatus(String formId, Integer status) {
        WFlowForm wFlowForm = new WFlowForm();
        wFlowForm.setId(formId);
        wFlowForm.setMbsBpmFlag(status);
        wFlowForm.setUpdateDate(DateUtils.getNow());
        wFlowForm.setUpdateBy(UserUtils.getCurrentUserId());
        wFlowFormService.updateById(wFlowForm);
    }

    /**
     * 采购方案变更
     *
     * @param wFlowFormId
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void changePurchasePlan(String wFlowFormId) {
        try {
            WFlowSubForm wFlowSubForm = new WFlowSubForm();
            wFlowSubForm.setFlowFormId(wFlowFormId);
            wFlowSubForm.setPurchaseSolutionStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_1_STATUS_1.getCode());
            wFlowSubForm.setPurchaseSolutionActionTime(DateUtils.getNow());
            wFlowSubFormService.updateByFormId(wFlowSubForm);

            String nodeName = sCommentConfigService.getValueByCode(CommentConfigEnum.P_PLAN_NODE_NAME_HISTORY_UPDATE.getCode());
            sHistoryCommentService.saveSHistoryComment(buildCommonHistory(wFlowFormId, wFlowFormId,
                    HistoryCommentModelTypeEnum.HistoryCommentModelType7.getCode(), "",
                    PurchaseActionNameEnum.PURCHASE_PLAN_2_2.getDesc(), nodeName, 0, false));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }


    /**
     * 流转统一处理
     *
     * @param flowTurnVO
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void FlowTurnCommon(FlowTurnVO flowTurnVO) {
        try {
            String handleUser = null;

            WFlowForm wFlowForm = wFlowFormService.selectById(flowTurnVO.getFlowFormId());
            if (flowTurnVO.getNodeCode() != WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode()
                    && !wFlowForm.getFlowFormSubStatus().contains(flowTurnVO.getNodeCode() + "")) {
                throw new RuntimeException("不是当前节点，请刷新重试", new ServiceThrowable());
            }
            if (StringUtils.isEmpty(flowTurnVO.getHandleUser())) {
                //PSpecialPurchasePlan pSpecialPurchasePlan = pSpecialPurchasePlanService.selectById(wFlowForm.getPurchasePlanId());
                handleUser = wFlowForm.getHandleUser();
            } else
                handleUser = flowTurnVO.getHandleUser();

            Map<String, Object> param = Maps.newHashMapWithExpectedSize(3);
            param.put("flowFormId", wFlowForm.getId());
            param.put("doneFlag", CommonConstants.UNDONG_FLAG);
            param.put("lineStatus", flowTurnVO.getNodeCode());
            List<WFlowFormSteps> currsets = wFlowFormStepsService.getWFlowFormStepsByCnd(param);
            if (CollectionUtils.isEmpty(currsets)) {
                throw new RuntimeException("重复处理", new ServiceThrowable());
            }
            WFlowFormSteps handleSteps = currsets.get(0);

            SMyDeals sMyDeals = new SMyDeals();
            sMyDeals.setRelatedId(flowTurnVO.getFlowFormId());
            sMyDeals.setActionType(workLineStatusMappingDealActionType(flowTurnVO.getNodeCode()));
            sMyDealsService.doneByEntityAndUsers(sMyDeals, null, "已处理");

            if (flowTurnVO.getGoFlag() == 2) {
                //if(sMyDeals.getDealSubType()==MyDealSubTypeEnum.ABORTIVE_LOOK_THROUGH.getCode()){
                if (flowTurnVO.getNodeCode() == WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode()) {
                    flowTurnVO.setGoFlag(PurchaseCommonEnum.FLOW_TURN_VAL.getCode() + wFlowForm.getAbortiveType());
                } else {
                    WFlowFormSteps wFlowFormSteps = wFlowFormStepsService.getWFlowFormStepsByFormAndTaskId(flowTurnVO.getFlowFormId(), handleSteps.getTaskId());
                    WFlowForm wFlowForm1 = new WFlowForm();
                    wFlowForm1.setAbortiveType(wFlowFormSteps.getLineStatus());
                    wFlowForm.setAbortiveType(wFlowFormSteps.getLineStatus());
                    wFlowForm1.setId(flowTurnVO.getFlowFormId());
                    wFlowForm1.setAbortiveApplyUserId(handleUser);
                    wFlowForm1.setAbortiveDesc(flowTurnVO.getReason());
                    wFlowForm1.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);
                    wFlowFormService.updateById(wFlowForm1);
                }
            } else {
                if (flowTurnVO.getNodeCode() == WorkFlowLineStatusEnum.LINE_STATUS_TENDER_BID.getCode()) {//询标
                    if (wFlowForm.getBackBidRounds() == PurchaseCommonEnum.BACK_ROUND_1.getCode()) {
                        flowTurnVO.setGoFlag(FlowGoflagEnum.X2P.getCode());
                    } else if (wFlowForm.getBackBidRounds() == PurchaseCommonEnum.BACK_ROUND_2.getCode()) {
                    } else if (wFlowForm.getBackBidRounds() == PurchaseCommonEnum.BACK_ROUND_5.getCode()) {
                    } else {
                        flowTurnVO.setGoFlag(FlowGoflagEnum.X2EL.getCode());
                    }
                } else if (flowTurnVO.getNodeCode() == WorkFlowLineStatusEnum.LINE_STATUS_TWO_BACK_BID.getCode()) {//二轮回标
                    if (wFlowForm.getBackBidRounds() == PurchaseCommonEnum.BACK_ROUND_3.getCode()) {//二轮一议 流转到商务谈判
                        flowTurnVO.setGoFlag(FlowGoflagEnum.EL2S.getCode());
                    }
                }
            }
            transferFlowProcess(wFlowForm.getProcessConfigId(), handleSteps.getTaskId(), UserUtils.getCurrentUserId(), flowTurnVO.getGoFlag());
            Map<String, Object> mapResult = activitiTaskService.getTaskIdAndNamesProcessInstanceId(wFlowForm.getProcInstanceId());
            String taskIds = StringUtils.object2StringNotNull(mapResult.get("TASK_IDS"));
            String taskNames = StringUtils.object2StringNotNull(mapResult.get("TASK_NAMES"));
            generateFlowGoneMyDeals(wFlowForm, handleUser, handleSteps.getTaskId(), wFlowForm.getTaskIds(), taskIds, taskNames, flowTurnVO);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        } finally {
            //很重要
            ThreadLocalWFlowFormSteps.getInstance().remove();
        }
    }

    public Integer workLineStatusMappingDealActionType(Integer lineStatus) {
        switch (lineStatus) {
            case 1:
                return MyDealActionTypeEnum.PURCHASE_PLAN.getCode();
            case 2:
                return MyDealActionTypeEnum.SUPPLIER_ENTRY.getCode();
            case 3:
                return MyDealActionTypeEnum.BIDDING_DOCUMENTS.getCode();
            case 4:
                return MyDealActionTypeEnum.SEND_BID.getCode();
            case 5:
                return MyDealActionTypeEnum.QUE_ANSWER.getCode();
            case 6:
                return MyDealActionTypeEnum.RETURN_BID.getCode();
            case 7:
                return MyDealActionTypeEnum.OPEN_BID.getCode();
            case 8:
                return MyDealActionTypeEnum.INQUIRING_BID.getCode();
            case 9:
                return MyDealActionTypeEnum.BUSINESS_NEGOTIATION.getCode();
            case 10:
                return MyDealActionTypeEnum.PING_BID.getCode();
            case 11:
                return MyDealActionTypeEnum.CALIBRATION.getCode();
            case 12:
                return MyDealActionTypeEnum.ABORTIVE_LOOK_THROUGH.getCode();
            case 13:
                return MyDealActionTypeEnum.TWO_RETURN_BID.getCode();
        }
        return 0;
    }

    /**
     * 延标
     *
     * @param delayBidVO
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public WFlowFormBidDelayHistory delayBid(DelayBidVO delayBidVO) {
        try {
            WFlowFormTimeNode wFlowFormTimeNode = new WFlowFormTimeNode();
            wFlowFormTimeNode.setFlowFormId(delayBidVO.getFlowFormId());
            if (delayBidVO.getBidDelayType() == PurchaseCommonEnum.DELAY_BID_TYPE_1.getCode()) {
                wFlowFormTimeNode.setBackBidDelay(delayBidVO.getEndTime());
            } else if (delayBidVO.getBidDelayType() == PurchaseCommonEnum.DELAY_BID_TYPE_2.getCode()) {
                wFlowFormTimeNode.setTwoRoundBackBidDelay(delayBidVO.getEndTime());
            } else if (delayBidVO.getBidDelayType() == PurchaseCommonEnum.DELAY_BID_TYPE_3.getCode()) {
                wFlowFormTimeNode.setBusinessNegoteReturnDelay(delayBidVO.getEndTime());
            } else if (delayBidVO.getBidDelayType() == PurchaseCommonEnum.DELAY_BID_TYPE_4.getCode()) {
                wFlowFormTimeNode.setBidEvaluationDelay(delayBidVO.getEndTime());
            }
            wFlowFormTimeNodeService.updateByFormId(wFlowFormTimeNode);

            WFlowFormBidDelayHistory wFlowFormBidDelayHistory = new WFlowFormBidDelayHistory();
            wFlowFormBidDelayHistory.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
            BeanUtils.copyProperties(delayBidVO, wFlowFormBidDelayHistory);
            wFlowFormBidDelayHistoryService.insert(wFlowFormBidDelayHistory);
            return wFlowFormBidDelayHistory;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 延标历史
     *
     * @param delayBidVO
     * @return
     */
    @Override
    public List<WFlowFormBidDelayHistory> delayBidHistory(DelayBidVO delayBidVO) {
        return wFlowFormBidDelayHistoryService.findByTypeAndFormId(delayBidVO.getFlowFormId(), delayBidVO.getBidDelayType());
    }


    public SHistoryComment buildCommonHistory(String relateId, String subId, int modeType,
                                              String commentConfig, String actionName, String nodeName, int agreeFlag, boolean needSelectTitle) {
        SHistoryComment historyComment = new SHistoryComment();
        historyComment.setBaseFeilds(UserUtils.getCurrentUserId(), "",
                CommonConstants.DEL_FLAG_NORMAL, true);
        historyComment.setModelType(modeType);
        historyComment.setSubRelatedId(subId);
        historyComment.setRelatedId(relateId);
        historyComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());
        if (needSelectTitle) {
            SCommentConfig sc = sCommentConfigService.getByCode(commentConfig);
            historyComment.setCommentContent(sc == null ? "" : sc.getConfigValue());
        } else {
            historyComment.setCommentContent(commentConfig);
        }

        historyComment.setActionName(actionName);
        historyComment.setSetupTime(DateUtils.getNow());
        historyComment.setNodeName(nodeName);
        historyComment.setAgreeFlag(agreeFlag);
        return historyComment;
    }


    /**
     * 格式化 标信息
     *
     * @param
     * @return RestReturnResult
     */
    public List<CalibrationInfoRspVO> backBidInfoFormat(List<ExtWFlowFormBackBid> wfbs) {
        List<CalibrationInfoRspVO> beans = Lists.newArrayList();
        int snTem = 0;
        CalibrationInfoRspVO vo = null;
        for (ExtWFlowFormBackBid w : wfbs) {
            if (w.getSegmentsNumber() != snTem) {
                snTem = w.getSegmentsNumber();
                vo = new CalibrationInfoRspVO();
                vo.setSegmentsNumber(snTem);
                vo.setFlowFormBackBids(Lists.newArrayList());
                beans.add(vo);
            }
            vo.getFlowFormBackBids().add(w);
        }
        return beans;
    }

    @Override
    public void updateBusinessInfo(ExtWFlowFormBackBid flowFormBackBid) {
        WFlowFormBackBid wFlowFormBackBid = wFlowFormBackBidService.selectById(flowFormBackBid.getId());
        //WFlowForm wFlowForm = wFlowFormService.selectById(flowFormBackBid.getFlowFormId());
        BeanUtils.copyProperties(flowFormBackBid, wFlowFormBackBid, getNullPropertyNames(flowFormBackBid));
        wFlowFormBackBid.setUpdateBy(UserUtils.getCurrentUserId());
        wFlowFormBackBid.setUpdateDate(DateUtils.getNow());

//		Integer flowType= wFlowForm.getFlowType();
//		if(flowType==PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_4.getCode()){
//			int qc = wFlowFormBackBid.getQualificationOrNot();
//			Double score = flowFormBackBid.getTechnicalScore();
//			int qc1 = score>=60d?CommonConstants.BID_OK:CommonConstants.BID_NO;
//			if (qc1!=qc) {
//				wFlowFormBackBid.setQualificationTime(DateUtils.getNow());
//				wFlowFormBackBid.setQualificationOrNot(qc1);
//			}
//		}
        SAttachment sAttachment = new SAttachment();
        if (StringUtils.isEmpty(flowFormBackBid.getBusinessBidId())) {
            if (StringUtils.isEmpty(flowFormBackBid.getBusinessBidUrl())) {
            } else {
                sAttachment.setBaseFeilds(UserUtils.getCurrentUserId(), null, 0, true);
                sAttachment.setFormId(flowFormBackBid.getFlowFormId());
                sAttachment.setRelatedId(flowFormBackBid.getId());
                sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_39.getCode());
                sAttachment.setAttachPath(flowFormBackBid.getBusinessBidUrl());
                sAttachment.setAttachName(flowFormBackBid.getBusinessBidUrlName());
                sAttachment.setAttachSize(flowFormBackBid.getBusinessBidSize());
                sAttachment.setAttachmentSubType(AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                //sAttachment.setCreateByUsername(UserUtils.getCurrentUserVo().getRealName());
                //sAttachment.setUpdateByUsername(UserUtils.getCurrentUserVo().getRealName());
                sAttachmentService.insert(sAttachment);
            }
        } else {
            sAttachment.setId(flowFormBackBid.getBusinessBidId());
            sAttachment.setAttachPath(flowFormBackBid.getBusinessBidUrl());
            sAttachment.setAttachName(flowFormBackBid.getBusinessBidUrlName());
            sAttachmentService.updateById(sAttachment);
        }
        wFlowFormBackBidService.updateById(wFlowFormBackBid);
    }

    /**
     * 更新定标信息
     *
     * @param flowFormBackBid
     * @return RestReturnResult
     */
    @Override
    public void updateCalibrationInfo(ExtWFlowFormBackBid flowFormBackBid) {
        WFlowFormBackBid wFlowFormBackBid = wFlowFormBackBidService.selectById(flowFormBackBid.getId());
        WFlowForm wFlowForm = wFlowFormService.selectById(flowFormBackBid.getFlowFormId());
        BeanUtils.copyProperties(flowFormBackBid, wFlowFormBackBid, getNullPropertyNames(flowFormBackBid));
        wFlowFormBackBid.setUpdateBy(UserUtils.getCurrentUserId());
        wFlowFormBackBid.setUpdateDate(DateUtils.getNow());

        Integer flowType = wFlowForm.getFlowType();
//		if(flowType==PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_4.getCode()){
//			int qc = wFlowFormBackBid.getQualificationOrNot();
//			Double score = flowFormBackBid.getTechnicalScore();
//			int qc1 = score>=60d?CommonConstants.BID_OK:CommonConstants.BID_NO;
//			if (qc1!=qc) {
//				wFlowFormBackBid.setQualificationTime(DateUtils.getNow());
//				wFlowFormBackBid.setQualificationOrNot(qc1);
//			}
//		}
        SAttachment sAttachment = new SAttachment();
        if (StringUtils.isEmpty(flowFormBackBid.getTechnicalBrightId())) {
            if (StringUtils.isEmpty(flowFormBackBid.getTechnicalBrightUrl())) {
            } else {
                sAttachment.setBaseFeilds(UserUtils.getCurrentUserId(), null, 0, true);
                sAttachment.setFormId(flowFormBackBid.getFlowFormId());
                sAttachment.setRelatedId(flowFormBackBid.getId());
                sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_23.getCode());
                sAttachment.setAttachPath(flowFormBackBid.getTechnicalBrightUrl());
                sAttachment.setAttachName(flowFormBackBid.getTechnicalBrightUrlName());
                sAttachment.setAttachSize(flowFormBackBid.getTechnicalBrightSize());
                sAttachment.setAttachmentSubType(AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                //sAttachment.setCreateByUsername(UserUtils.getCurrentUserVo().getRealName());
                //sAttachment.setUpdateByUsername(UserUtils.getCurrentUserVo().getRealName());
                sAttachmentService.insert(sAttachment);
            }
        } else {
            sAttachment.setId(flowFormBackBid.getTechnicalBrightId());
            sAttachment.setAttachPath(flowFormBackBid.getTechnicalBrightUrl());
            sAttachment.setAttachName(flowFormBackBid.getTechnicalBrightUrlName());
            sAttachmentService.updateById(sAttachment);
        }

        sAttachment = new SAttachment();
        if (StringUtils.isEmpty(flowFormBackBid.getBusinessBidId())) {
            if (StringUtils.isEmpty(flowFormBackBid.getBusinessBidUrl())) {
            } else {
                sAttachment.setBaseFeilds(UserUtils.getCurrentUserId(), null, 0, true);
                sAttachment.setFormId(flowFormBackBid.getFlowFormId());
                sAttachment.setRelatedId(flowFormBackBid.getId());

                sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_25.getCode());
                sAttachment.setAttachPath(flowFormBackBid.getBusinessBidUrl());
                sAttachment.setAttachName(flowFormBackBid.getBusinessBidUrlName());
                sAttachment.setAttachSize(flowFormBackBid.getBusinessBidSize());
                sAttachment.setAttachmentSubType(AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                //sAttachment.setCreateByUsername(UserUtils.getCurrentUserVo().getRealName());
                //sAttachment.setUpdateByUsername(UserUtils.getCurrentUserVo().getRealName());
                sAttachmentService.insert(sAttachment);
            }
        } else {
            sAttachment.setId(flowFormBackBid.getBusinessBidId());
            sAttachment.setAttachPath(flowFormBackBid.getBusinessBidUrl());
            sAttachment.setAttachName(flowFormBackBid.getBusinessBidUrlName());
            sAttachmentService.updateById(sAttachment);
        }
        wFlowFormBackBidService.updateById(wFlowFormBackBid);
    }

    /**
     * 新增询标问卷
     *
     * @param inquiringBidAnswerReqVO
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void addInquiringBidAnswer(InquiringBidAnswerReqVO inquiringBidAnswerReqVO) {
        try {
            WFlowFormInquiringBid wFlowFormInquiringBid = new WFlowFormInquiringBid();
            wFlowFormInquiringBid.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
            wFlowFormInquiringBid.setReadOrNot(CommonConstants.BID_NO);
            wFlowFormInquiringBid.setSupplierId(inquiringBidAnswerReqVO.getSupplierId());
            wFlowFormInquiringBid.setFlowFormId(inquiringBidAnswerReqVO.getFormId());
            wFlowFormInquiringBidService.insert(wFlowFormInquiringBid);
            inquiringBidAnswerReqVO.getAttachment().setRelatedId(wFlowFormInquiringBid.getId());
            inquiringBidAnswerReqVO.getAttachment().setFormId(inquiringBidAnswerReqVO.getFormId());
            inquiringBidAnswerReqVO.getAttachment().setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_27.getCode());
            sAttachmentService.insert(inquiringBidAnswerReqVO.getAttachment());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 删除询标问卷
     *
     * @param id
     */
    @Override
    public void deleteInquiringBidAnswer(String id) {
        wFlowFormInquiringBidService.deleteById(id);
    }

    /**
     * 发送询标文件
     *
     * @param id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void sendInquiringBidAnswer(String id) {
        try {
            WFlowFormInquiringBid wFlowFormInquiringBid = wFlowFormInquiringBidService.selectById(id);
            WFlowForm wFlowForm = wFlowFormService.selectById(wFlowFormInquiringBid.getFlowFormId());
            SMessageTemplate sMessageTemplate = sMessageTemplateService.getByMsgType(MessagesMsgTypeEnum.MsgType10.getCode());
            String contentTemplate = sMessageTemplate.getMsgContent();
            String title = sMessageTemplate.getMsgName();
            SMessages sMessages = new SMessages();
            sMessages.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
            sMessages.setBidSupplierId(wFlowFormInquiringBid.getSupplierId());
            sMessages.setUserIds(wFlowFormInquiringBid.getSupplierId());

            sMessages.setFlowFormId(wFlowFormInquiringBid.getFlowFormId());
            sMessages.setReadFlag(CommonConstants.NO_INTEGER);
            sMessages.setMsgType(MessagesMsgTypeEnum.MsgType10.getCode());
            sMessages.setMsgContent(MessageFormat.format(contentTemplate, wFlowForm.getPurchaseItemName()));
            sMessages.setMsgTitle(MessageFormat.format(title, wFlowForm.getPurchaseItemName()));
            sMessagesService.insert(sMessages);

            wFlowFormInquiringBid.setUpdateBy(UserUtils.getCurrentUserId());
            wFlowFormInquiringBid.setUpdateDate(DateUtils.getNow());
            wFlowFormInquiringBid.setInquiringBidSendTime(DateUtils.getNow());
            wFlowFormInquiringBidService.updateById(wFlowFormInquiringBid);

            SAttachment sAttachment = new SAttachment();
            sAttachment.setFormId(wFlowForm.getId());
            sAttachment.setRelatedId(wFlowFormInquiringBid.getId());
            sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_27.getCode());
            sAttachmentService.updateSendTime(sAttachment);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 发起技术标评分
     *
     * @param technicaBidScoreReqVO
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void initiatingTechnicalMarkScore(TechnicaBidScoreReqVO technicaBidScoreReqVO) {
        try {
            WFlowSubForm wFlowSubForm1 = wFlowSubFormService.selectByFormId(technicaBidScoreReqVO.getFormId());
            if (wFlowSubForm1.getTechnicalBidScoreFlag() != null && wFlowSubForm1.getTechnicalBidScoreFlag() == CommonConstants.YES_INTEGER) {
                throw new RuntimeException("不允许重复发起", new ServiceThrowable());
            }

            WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(technicaBidScoreReqVO.getFormId());
            wFlowFormTimeNode.setInquiringBidDelay(technicaBidScoreReqVO.getDelayTime());
            wFlowFormTimeNodeService.updateById(wFlowFormTimeNode);

            WFlowSubForm wFlowSubForm = new WFlowSubForm();
            wFlowSubForm.setFlowFormId(technicaBidScoreReqVO.getFormId());
            wFlowSubForm.setTechnicalBidScoreFlag(CommonConstants.YES_INTEGER);
            wFlowSubForm.setTechnicalBidScoreTime(DateUtils.getNow());

            wFlowSubFormService.updateByFormId(wFlowSubForm);

            List<WFlowFormPurchaseTeam> wFlowFormPurchaseTeams = wFlowFormPurchaseTeamService.
                    getTeamByFlowFormIdAndJob(technicaBidScoreReqVO.getFormId(), PurchaseCommonEnum.PURCHASE_JOB_3.getCode(), PurchaseCommonEnum.PURCHASE_JOB_4.getCode());

            WFlowForm wFlowForm = wFlowFormService.selectById(technicaBidScoreReqVO.getFormId());

            if (wFlowFormPurchaseTeams == null || wFlowFormPurchaseTeams.size() == 0)
                throw new RuntimeException("采购小组为空", new ServiceThrowable());
            List<ExtWFlowFormIbTechScore> extWFlowFormIbTechScores = wFlowFormIbTechScoreService.getExtByFormId(technicaBidScoreReqVO.getFormId());
            if (extWFlowFormIbTechScores == null || extWFlowFormIbTechScores.size() == 0)
                throw new RuntimeException("系统异常", new ServiceThrowable());
            List<SSuppliersCategoryTemplate> sSuppliersCategoryTemplateList = sSuppliersCategoryTemplateService.
                    selectByCategoryIdAndTypes(wFlowForm.getPurchaseClassification(),
                            SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_BRIGHT_MARK.getCode(),
                            SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_DARK_MARK.getCode(),
                            SuppliersCategoryTemplateTypeEnum.SCORE_INTERVIEW_BY_MANAGER.getCode());
            for (WFlowFormPurchaseTeam w : wFlowFormPurchaseTeams) {

                List<WFlowFormTechScoreDetals> lstWFlowFormTechScoreDetals = new ArrayList<>();
//				boolean score_technology_bright_mark=false;
//				boolean score_technology_dark_mark=false;
//				boolean score_interview_by_manager=false;
                for (SSuppliersCategoryTemplate sSuppliersCategoryTemplate : sSuppliersCategoryTemplateList) {
                    for (ExtWFlowFormIbTechScore extWFlowFormIbTechScore : extWFlowFormIbTechScores) {
                        if (w.getUserId().equals(extWFlowFormIbTechScore.getUserId())) {
                            WFlowFormTechScoreDetals wFlowFormTechScoreDetals = new WFlowFormTechScoreDetals();
                            BeanUtils.copyProperties(sSuppliersCategoryTemplate, wFlowFormTechScoreDetals);
                            wFlowFormTechScoreDetals.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                            wFlowFormTechScoreDetals.setEvaluatorUserId(extWFlowFormIbTechScore.getUserId());
//						wFlowFormTechScoreDetals.setEvaluationDepartmentId(extWFlowFormIbTechScore.getDepartmentId());
                            wFlowFormTechScoreDetals.setFlowFormId(technicaBidScoreReqVO.getFormId());
                            wFlowFormTechScoreDetals.setId(IdGen.uuid());
                            wFlowFormTechScoreDetals.setSupplierId(extWFlowFormIbTechScore.getSupplierId());
                            lstWFlowFormTechScoreDetals.add(wFlowFormTechScoreDetals);
                        }
                    }
//					if(SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_BRIGHT_MARK.getCode()==sSuppliersCategoryTemplate.getTemplateType()){
//						score_technology_bright_mark=true;
//					}else if(SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_DARK_MARK.getCode()==sSuppliersCategoryTemplate.getTemplateType()){
//						score_technology_dark_mark=true;
//					}else if(SuppliersCategoryTemplateTypeEnum.SCORE_INTERVIEW_BY_MANAGER.getCode()==sSuppliersCategoryTemplate.getTemplateType()){
//						score_interview_by_manager=true;
//					}
                }

                //if(score_technology_bright_mark&&score_technology_dark_mark&&score_interview_by_manager){
                wFlowFormTechScoreDetalsService.insertBatch(lstWFlowFormTechScoreDetals);
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.PURCHASE_INITIATING_TECHNICAL_MARK_SCORE_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(technicaBidScoreReqVO.getFormId(),
                        technicaBidScoreReqVO.getFormId(), MyDealSubTypeEnum.INQUIRING_BID.getCode(),
                        MyDealActionTypeEnum.INQUIRING_BID_SCORE.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName())
                        , w.getUserId()
                        , wFlowFormTimeNode.getTechnicalBidEvaluation(), null));

//				}else{
//					throw new RuntimeException("模板不存在",new ServiceThrowable());
//				}
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }


    /**
     * 废标
     *
     * @param selectBidUnitReqVo
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void abandonedBid(SelectBidUnitReqVo selectBidUnitReqVo) {
        try {
            List<String> ids = StringUtils.getListBySplitStr(selectBidUnitReqVo.getIds());
            WFlowFormBackBid w = new WFlowFormBackBid();
            if (selectBidUnitReqVo.getFlowFormId() != null) {
                w.setAbandonedBidOrNot(CommonConstants.NO_INTEGER);
                wFlowFormBackBidService.update(w, new EntityWrapper<WFlowFormBackBid>()
                        .eq("flow_form_id", selectBidUnitReqVo.getFlowFormId()).eq("qualification_or_not", CommonConstants.YES_INTEGER));
            }
            for (String id : ids) {
                WFlowFormBackBid ww = new WFlowFormBackBid();
                ww.setId(id);
                ww.setAbandonedBidOrNot(CommonConstants.YES_INTEGER);
                ww.setUpdateDate(DateUtils.getNow());
                wFlowFormBackBidService.updateById(ww);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 废标列表
     *
     * @return
     */
    @Override
    public List<ExtWFlowFormBackBid> selectAbandonedBidList(String formId) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("formId", formId);
        params.put("backBidOrNot", CommonConstants.YES_INTEGER);
        params.put("scoreGE", 60d);
        return wFlowFormBackBidService.getExtBackBidByMap(params);
    }

    @Override
    public List<ExtWFlowFormBackBid> selectBidUnitList(String formId) {
        WFlowForm wFlowForm = wFlowFormService.selectById(formId);
        Integer flowType = wFlowForm.getFlowType();
        Map<String, Object> param = Maps.newHashMap();
        if (flowType != PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_4.getCode() &&
                flowType != PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_5.getCode() &&
                flowType != PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_6.getCode())
            param.put("backBidOrNot", CommonConstants.YES_INTEGER);
        param.put("formId", formId);
        param.put("abandonedBidOrNot", CommonConstants.NO_INTEGER);
        param.put("qualificationOrNot", CommonConstants.YES_INTEGER);
        return wFlowFormBackBidService.getExtBackBidByMap(param);
    }


    /**
     * 一事一议历史
     *
     * @param wFlowFormDiscussionHistory
     * @return
     */
    @Override

    public List<ExtWFlowFormDiscussionHistory> getOneThingAndOneDiscussionData(WFlowFormDiscussionHistory wFlowFormDiscussionHistory) {
        return wFlowFormDiscussionHistoryService.getExtByFormIdAndType(wFlowFormDiscussionHistory.getFlowFormId(),
                wFlowFormDiscussionHistory.getDiscussionType());
    }

    /**
     * 一事一议提交
     *
     * @param wFlowFormDiscussionHistory
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void submitOneThingAndOneDiscussion(ExtWFlowFormDiscussionHistory wFlowFormDiscussionHistory) {
        try {
            SAttachment sAttachment = wFlowFormDiscussionHistory.getAttachment();
            if (StringUtils.isEmpty(wFlowFormDiscussionHistory.getId())) {
                wFlowFormDiscussionHistory.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                wFlowFormDiscussionHistory.setDiscussionStartTime(DateUtils.getNow());
                wFlowFormDiscussionHistory.setFirstFlag(CommonConstants.YES_INTEGER);
                wFlowFormDiscussionHistoryService.insert(wFlowFormDiscussionHistory);
            } else {
                wFlowFormDiscussionHistoryService.updateById(wFlowFormDiscussionHistory);
            }
            if (StringUtils.isEmpty(sAttachment.getId())) {
                if (StringUtils.isNotEmpty(sAttachment.getAttachPath())) {
                    sAttachment.setFormId(wFlowFormDiscussionHistory.getFlowFormId());
                    sAttachment.setRelatedId(wFlowFormDiscussionHistory.getId());
                    sAttachment.setAttachmentSubType(AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                    sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_43.getCode());
                    SessionUserVo sessionUserVo = UserUtils.getCurrentUserVo();
                    sAttachment.setCreateByUsername(sessionUserVo.getRealName());
                    sAttachment.setUpdateByUsername(sessionUserVo.getRealName());
                    sAttachmentService.insert(sAttachment);
                }
            } else if (StringUtils.isEmpty(sAttachment.getAttachPath())) {
                sAttachment.setDelFlag(CommonConstants.DEL_FLAG_DELETE);
                sAttachmentService.updateById(sAttachment);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }


    /**
     * 新增定标信息
     *
     * @param calibrationInfoReqVO
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public List<CalibrationInfoRspVO> addCalibrationInfo(CalibrationInfoReqVO calibrationInfoReqVO) {
        List<CalibrationInfoRspVO> list = Lists.newArrayList();
        WFlowForm wFlowForm = wFlowFormService.selectById(calibrationInfoReqVO.getFlowFormId());
        int sn = wFlowForm.getSegmentsNumber() == null ? 1 : wFlowForm.getSegmentsNumber();
        int tem = 0;
        CalibrationInfoRspVO calibrationInfoRspVO = null;
        for (int i = 1; i <= sn; i++) {
            WFlowFormBackBid wFlowFormBackBid = buildWFlowFormBackBid(wFlowForm.getId(), calibrationInfoReqVO.getSupplierId(),
                    CommonConstants.AWARD_BID, CommonConstants.BID_OK, i);
            wFlowFormBackBidService.insert(wFlowFormBackBid);
            if (i != tem) {
                calibrationInfoRspVO = new CalibrationInfoRspVO(i);
                List<ExtWFlowFormBackBid> wFlowFormBackBids = Lists.newArrayList();
                calibrationInfoRspVO.setFlowFormBackBids(wFlowFormBackBids);
                list.add(calibrationInfoRspVO);
                tem = i;
            }
            ExtWFlowFormBackBid extWFlowFormBackBid = (ExtWFlowFormBackBid) wFlowFormBackBid;
            extWFlowFormBackBid.setSupplierName(sSuppliersService.getById(calibrationInfoReqVO.getSupplierId()).getCompanyName());
            calibrationInfoRspVO.getFlowFormBackBids().add(extWFlowFormBackBid);
        }
        return list;
    }

    /**
     * 删除 定标信息
     *
     * @param calibrationInfoReqVO
     * @return
     */
    @Override
    public void deleteCalibrationInfo(CalibrationInfoReqVO calibrationInfoReqVO) {
        wFlowFormBackBidService.deleteByformIdOrSupplierId(calibrationInfoReqVO);
    }

    /**
     * 引用战略协议
     *
     * @param quoteStrategicProtocolVO
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public List<ExtWFlowFormStrategicProtocol> quoteStrategicProtocol(QuoteStrategicProtocolVO quoteStrategicProtocolVO) {
        try {
            List<String> ids = StringUtils.getListBySplitStr(quoteStrategicProtocolVO.getIds());
            return extwlowFormStrategicProtocolService.inserByProtocolIds(ids, quoteStrategicProtocolVO.getWflowFormId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 查询保证金列表
     *
     * @param formId
     * @return
     */
    @Override
    public List<ExtWFlowFormCashDeposit> selectCashDeposit(String formId) {
        return wFlowFormCashDepositService.getExtByFormId(formId);
    }


    /**
     * 退保证金
     *
     * @param id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void depositCashBack(String id) {
        try {
//            wFlowFormCashDepositService.updateRefundStatus(id, RefundCashierStatusEnum.REFUNDING.getCode());
            // 直接更新为保证金已退
            wFlowFormCashDepositService.updateRefundStatus(id, RefundCashierStatusEnum.REFUNDED.getCode());

            //TODO 发送到出纳
//			WFlowFormCashDeposit wFlowFormCashDeposit = wFlowFormCashDepositService.selectById(id);
//			DepositConfirmRequestEntity entity = new DepositConfirmRequestEntity();
//			BeanUtils.copyProperties(wFlowFormCashDeposit, entity);
//			List<DepositConfirmRequestEntity> checkByFlowList = new ArrayList<DepositConfirmRequestEntity>();
//			checkByFlowList.add(entity);
//			//退保证金
//			this.dealMBSToDoList(checkByFlowList, "C");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    @Override
    public AnswerNodeRspVO findAnswerNodeData(String formId) {
        AnswerNodeRspVO answerNodeRspVO = new AnswerNodeRspVO();
        AnswerNodeBasisVO answerNodeBasisVO = new AnswerNodeBasisVO();
        answerNodeBasisVO.setFormId(formId);
        WFlowForm wFlowForm = wFlowFormService.selectById(formId);
        answerNodeBasisVO.setCountSignStatus(wFlowForm.getSupplierReferersStatus());
        answerNodeBasisVO.setPurchaseItemName(wFlowForm.getPurchaseItemName());
        WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(formId);
        answerNodeBasisVO.setAnswers(wFlowFormTimeNode.getAnswers());
        answerNodeBasisVO.setQuestions(wFlowFormTimeNode.getQuestions());
        answerNodeRspVO.setAnswerNodeBasisVO(answerNodeBasisVO);
        Map<String, Object> map = new HashMap<>();
        map.put("formId", formId);
        map.put("attType", AttachmentTypeEnum.ATTACHMENT_TYPE_20.getCode());
        answerNodeRspVO.setExtWFlowFormSuppliersQuestions(wFlowFormSuppliersQuestionService.findExtByMap(map));
        answerNodeRspVO.setAttachments(sAttachmentService.getByFormIdAndAttachmentType(formId,
                AttachmentTypeEnum.ATTACHMENT_TYPE_21.getCode(), null));
        answerNodeRspVO.setFlowFormQaCountSigns(wFlowFormQaCountSignService.selectByFormIdAndRelateId(formId, null, PurchaseCommonEnum.COUNT_SIGN_DAYI.getCode(), null));
        return answerNodeRspVO;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void qaCountSign(QaCountSignReqVO qaCountSignReqVO) {
        try {
            WFlowForm w = wFlowFormService.selectById(qaCountSignReqVO.getFlowFormId());
            List<WFlowFormPurchaseTeam> teams = wFlowFormPurchaseTeamService.getTeamByFlowFormId(qaCountSignReqVO.getFlowFormId());
            String subRealteId = qaCountSignReqVO.getRelatedId();
            int actionType = MyDealActionTypeEnum.ANSWER_COUNT_SIGN.getCode();
            String title = CommentConfigEnum.PURCHASE_ANSWER_COUNT_SIGN_DEAL.getCode();
            int type = qaCountSignReqVO.getCountSignType();
            if (type == PurchaseCommonEnum.COUNT_SIGN_BUYI.getCode()) {
                actionType = MyDealActionTypeEnum.QUE_COUNT_SIGN.getCode();
                title = CommentConfigEnum.PURCHASE_QUESTION_COUNT_SIGN_DEAL.getCode();
            }
            SCommentConfig sc = sCommentConfigService.getByCode(title);
            title = MessageFormat.format(sc.getConfigValue(), w.getPurchaseItemName());
            if (StringUtils.isEmpty(subRealteId)) {
                subRealteId = qaCountSignReqVO.getFlowFormId();
            }
            Integer times = wFlowFormQaCountSignService.selectMaxTimesByFormIdAndRelate(qaCountSignReqVO.getFlowFormId(), qaCountSignReqVO.getRelatedId(), qaCountSignReqVO.getCountSignType());
            for (WFlowFormPurchaseTeam wpt : teams) {
                SMyDeals sMyDeals = buildCommonDeals(qaCountSignReqVO.getFlowFormId(), subRealteId,
                        MyDealSubTypeEnum.QUE_ANSWER.getCode(), actionType, title, wpt.getUserId(),
                        null, null);
                sMyDealsService.insert(sMyDeals);
                //插入会签历史
                WFlowFormQaCountSign wFlowFormQaCountSign = new WFlowFormQaCountSign();
                wFlowFormQaCountSign.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                wFlowFormQaCountSign.setFlowFormId(qaCountSignReqVO.getFlowFormId());
                wFlowFormQaCountSign.setRelatedId(subRealteId);
                wFlowFormQaCountSign.setPassOrNot(null);
                wFlowFormQaCountSign.setCountSignType(qaCountSignReqVO.getCountSignType());
                wFlowFormQaCountSign.setCompanyId(wpt.getCompanyId());
                wFlowFormQaCountSign.setCompanyName(wpt.getCompanyName());
                wFlowFormQaCountSign.setUserId(wpt.getUserId());
                wFlowFormQaCountSign.setUserName(wpt.getUserName());
                wFlowFormQaCountSign.setDepartmentId(wpt.getDepartmentId());
                wFlowFormQaCountSign.setDepartmentName(wpt.getDepartmentName());
                wFlowFormQaCountSign.setPurchaseJob(wpt.getPurchaseJob());
                wFlowFormQaCountSign.setPositionName(wpt.getPositionName());
                wFlowFormQaCountSign.setCountSignTimes(times + 1);
                wFlowFormQaCountSignService.insert(wFlowFormQaCountSign);

            }
            if (qaCountSignReqVO.getCountSignType() == PurchaseCommonEnum.COUNT_SIGN_BUYI.getCode()) {
                //更新补遗会签状态
                WFlowFormAddendumReferers wFlowFormAddendumReferers = new WFlowFormAddendumReferers();
                wFlowFormAddendumReferers.setId(qaCountSignReqVO.getRelatedId());
                wFlowFormAddendumReferers.setAddendumStatus(PurchaseCommonEnum.ADDENDUM_STATUS_QA.getCode());
                wFlowFormAddendumReferers.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);

                wFlowFormAddendumReferersService.updateById(wFlowFormAddendumReferers);
            } else {
                WFlowForm wFlowForm = new WFlowForm();
                wFlowForm.setId(qaCountSignReqVO.getFlowFormId());
                wFlowForm.setSupplierReferersStatus(PurchaseCommonEnum.ADDENDUM_STATUS_QA.getCode());
                wFlowForm.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);

                wFlowFormService.updateById(wFlowForm);
            }


        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }


    /**
     * 中标通知书
     *
     * @param formId
     * @return
     */
    @Override
    public BidWinningNoticeRspVO bidWinningNoticeList(String formId) {
        BidWinningNoticeRspVO bidWinningNoticeRspVO = new BidWinningNoticeRspVO();
        bidWinningNoticeRspVO.setNotices(wFlowFormBidNoticeThanksService.getExtByFormIdAndType(formId, PurchaseCommonEnum.NOTICE_TYPE.getCode()));
        bidWinningNoticeRspVO.setThanks(wFlowFormBidNoticeThanksService.getExtByFormIdAndType(formId, PurchaseCommonEnum.THANK_TYPE.getCode()));
        return bidWinningNoticeRspVO;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void submitCountSignResult(DealRequestVO dealRequestVO) {
        try {
            SMyDeals sMyDeals = sMyDealsService.selectUntreatedById(dealRequestVO.getId());
            String formId = sMyDeals.getRelatedId();
            WFlowFormPurchaseTeam wpt = wFlowFormPurchaseTeamService.getTeamByFormIdAndUserId(formId, sMyDeals.getUserId());
            Integer actionType = sMyDeals.getActionType();
            Integer countSignType = PurchaseCommonEnum.COUNT_SIGN_BUYI.getCode();
            if (actionType == MyDealActionTypeEnum.ANSWER_COUNT_SIGN.getCode()) {
                countSignType = PurchaseCommonEnum.COUNT_SIGN_DAYI.getCode();
            }
            Integer countTimes = wFlowFormQaCountSignService.selectMaxTimesByFormIdAndRelate(formId, sMyDeals.getSubRelatedId(), countSignType);
            List<WFlowFormQaCountSign> allWFlowFormQaCountSigns = wFlowFormQaCountSignService.
                    selectByFormIdAndRelateId(formId, sMyDeals.getSubRelatedId(), countSignType, countTimes);

            Integer allTeamsCount = allWFlowFormQaCountSigns.size();
            int agreeSum = 0;
            int noHandel = 0;
            for (WFlowFormQaCountSign wFlowFormQaCountSign : allWFlowFormQaCountSigns) {
                if (wFlowFormQaCountSign.getUserId().equals(UserUtils.getCurrentUserId()) && wFlowFormQaCountSign.getPassOrNot() != null) {
                    throw new RuntimeException("重复提交会签");
                }
                Integer passOrNot = wFlowFormQaCountSign.getPassOrNot();
                if (passOrNot == null) noHandel++;
                else if (passOrNot == CommonConstants.YES_INTEGER) agreeSum++;

            }
            if (noHandel == 1) {//全部审批人员都完成了审批
                Integer countSignStatus = CommonConstants.NO_INTEGER;
                if (dealRequestVO.getAgreeFlag() == CommonConstants.DEAL_OK && agreeSum == allTeamsCount - 1) {
                    countSignStatus = CommonConstants.YES_INTEGER;
                }
                if (countSignType == PurchaseCommonEnum.COUNT_SIGN_BUYI.getCode())
                    wFlowFormAddendumReferersService.updateCountResultById(sMyDeals.getSubRelatedId(), countSignStatus);
                else {
                    WFlowForm wFlowForm = new WFlowForm();
                    wFlowForm.setId(formId);
                    wFlowForm.setSupplierReferersStatus(countSignStatus == CommonConstants.NO_INTEGER ?
                            PurchaseCommonEnum.ADDENDUM_STATUS_START.getCode() : PurchaseCommonEnum.ADDENDUM_STATUS_YES.getCode());
                    wFlowFormService.updateById(wFlowForm);
                }
            }

            //更新会签结果
            WFlowFormQaCountSign wFlowFormQaCountSign = new WFlowFormQaCountSign();
            wFlowFormQaCountSign.setFlowFormId(formId);
            wFlowFormQaCountSign.setPassOrNot(dealRequestVO.getAgreeFlag() == CommonConstants.DEAL_BACK ?
                    CommonConstants.NO_INTEGER : CommonConstants.YES_INTEGER);
            wFlowFormQaCountSign.setRelatedId(sMyDeals.getSubRelatedId());
            wFlowFormQaCountSign.setCountSignType(countSignType);
            wFlowFormQaCountSign.setCountSignTimes(countTimes);
            wFlowFormQaCountSign.setUserId(UserUtils.getCurrentUserId());
            wFlowFormQaCountSignService.updateStatusByEntity(wFlowFormQaCountSign);
            //更新代办
            sMyDealsService.deleteSmyDealsById(sMyDeals.getId());

        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    WFlowFormBackBid buildWFlowFormBackBid(String flowFormId, String supplierId,
                                           int AwardBidOrNot, int QualificationOrNot, int sn) {
        WFlowFormBackBid wFlowFormBackBid = new WFlowFormBackBid();
        wFlowFormBackBid.setBaseFeilds(UserUtils.getCurrentUserId(), "",
                CommonConstants.DEL_FLAG_NORMAL, true);
        wFlowFormBackBid.setFlowFormId(flowFormId);
        wFlowFormBackBid.setSupplierId(supplierId);
        wFlowFormBackBid.setBackBidOrNot(CommonConstants.NO_INTEGER);
        wFlowFormBackBid.setRoundTwoBackBidOrNot(CommonConstants.NO_INTEGER);
        wFlowFormBackBid.setAwardBidOrNot(AwardBidOrNot);
        wFlowFormBackBid.setQualificationOrNot(QualificationOrNot);
        wFlowFormBackBid.setSegmentsNumber(sn);
        return wFlowFormBackBid;
    }

    /**
     * 邀请函详情
     *
     * @param formId
     */
    @Override
    public InvitationDetailResponse invitationDetail(String formId) {
        InvitationDetailResponse invitationDetailResponse = new InvitationDetailResponse();
        List<WFlowFormBidCandidateUnit> wFlowFormBidCandidateUnits = wFlowFormBidCandidateUnitService.findByFormIdAndType(formId,
                PurchaseCommonEnum.CANDIDATE_TYPE_PUT.getCode());
        WFlowForm wFlowForm = wFlowFormService.selectById(formId);
//		SMessageTemplate sMessageTemplate = sMessageTemplateService.getByMsgType(MessagesMsgTypeEnum.MsgType4.getCode());
//		invitationDetailResponse.setTitle(sMessageTemplate.getMsgName());
//		String body = sMessageTemplate.getMsgContent();
//		body.replace(MessagesTemplateParamEnum.INVATION_1.getCode(),sSuppliers.getCompanyName())
//				.replace(MessagesTemplateParamEnum.INVATION_2.getCode(),wFlowForm.getPurchaseItemName())
//				.replace(MessagesTemplateParamEnum.INVATION_3.getCode(),wFlowForm.getOriginatorUser())
//				.replace(MessagesTemplateParamEnum.INVATION_4.getCode(),String.valueOf(wFlowForm.getBidBounds()))
//				.replace(MessagesTemplateParamEnum.INVATION_5.getCode(),wFlowForm.getPayeeUnit())
//				.replace(MessagesTemplateParamEnum.INVATION_6.getCode(),wFlowForm.getRemittanceAccount())
//				.replace(MessagesTemplateParamEnum.INVATION_7.getCode(),wFlowForm.getOpenedBank());
//		invitationDetailResponse.setBody(body);
        List<String> ids = Lists.newArrayListWithCapacity(wFlowFormBidCandidateUnits.size());
        for (WFlowFormBidCandidateUnit w : wFlowFormBidCandidateUnits) {
            ids.add(sSuppliersService.getById(w.getSuppliersId()).getCompanyName());
        }
        invitationDetailResponse.setCompanyName(ids.stream().collect(Collectors.joining(",")));
        invitationDetailResponse.setPurchaseItemName(wFlowForm.getPurchaseItemName());
        invitationDetailResponse.setOriginatorUser(wFlowForm.getOriginatorUser());
        invitationDetailResponse.setBidBounds(wFlowForm.getBidBounds());
        invitationDetailResponse.setPayeeUnit(wFlowForm.getPayeeUnit());
        invitationDetailResponse.setRemittanceAccount(wFlowForm.getRemittanceAccount());
        invitationDetailResponse.setOpenedBank(wFlowForm.getOpenedBank());
        return invitationDetailResponse;
    }


    /**
     * 发送补遗文件
     *
     * @param id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void sendQuestionFile(String id) {
        try {
            WFlowFormAddendumReferers wFlowFormAddendumReferers = wFlowFormAddendumReferersService.selectById(id);
            WFlowForm wFlowForm = wFlowFormService.selectById(wFlowFormAddendumReferers.getFlowFormId());
            SMessageTemplate sMessageTemplate = sMessageTemplateService.getByMsgType(MessagesMsgTypeEnum.MsgType9.getCode());
            Integer status = Integer.parseInt(wFlowForm.getFlowFormSubStatus());
            List<String> suppilerIds = null;
            if (status <= WorkFlowLineStatusEnum.LINE_STATUS_BACK_BID.getCode()) {
                suppilerIds = wFlowFormSupplierEntryService.getSupplierIdsWithAgree(wFlowForm.getId());
            } else {
                Map<String, Object> param = Maps.newHashMap();
                param.put("formId", wFlowForm.getId());
                param.put("backBidOrNot", CommonConstants.YES_INTEGER);
                suppilerIds = wFlowFormBackBidService.selectSupplieridsByMap(param);
            }
            String contentTemplate = sMessageTemplate.getMsgContent();
            String title = sMessageTemplate.getMsgName();
            for (String supplierId : suppilerIds) {
                SMessages sMessages = new SMessages();
                sMessages.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                sMessages.setBidSupplierId(id);
                sMessages.setUserIds(supplierId);
                sMessages.setFlowFormId(wFlowForm.getId());
                sMessages.setReadFlag(CommonConstants.NO_INTEGER);
                sMessages.setMsgType(MessagesMsgTypeEnum.MsgType9.getCode());
                sMessages.setMsgContent(MessageFormat.format(contentTemplate, wFlowForm.getPurchaseItemName()));
                sMessages.setMsgTitle(MessageFormat.format(title, wFlowForm.getPurchaseItemName()));
                sMessagesService.insert(sMessages);
            }
            WFlowFormAddendumReferers wFlowFormAddendumReferers1 = new WFlowFormAddendumReferers();
            wFlowFormAddendumReferers1.setId(id);
            wFlowFormAddendumReferers1.setAddendumStatus(PurchaseCommonEnum.ASK_FILE_SEND_END.getCode());
            wFlowFormAddendumReferers1.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.NO_INTEGER, false);
            wFlowFormAddendumReferers1.setAddendumSendTime(DateUtils.getNow());
            wFlowFormAddendumReferersService.updateById(wFlowFormAddendumReferers1);

            //跟新答疑附件发送时间
            SAttachment sAttachment = new SAttachment();
            sAttachment.setFormId(wFlowForm.getId());
            sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_21.getCode());
            sAttachmentService.updateSendTime(sAttachment);

        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }


    /**
     * 发送答疑文件
     *
     * @param formId
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void sendAskFile(String formId) {
        try {
            WFlowForm wFlowForm1 = wFlowFormService.selectById(formId);
            List<String> suppilerIds = wFlowFormSupplierEntryService.getSupplierIdsWithAgree(formId);
            SMessageTemplate sMessageTemplate = sMessageTemplateService.getByMsgType(MessagesMsgTypeEnum.MsgType8.getCode());
            String contentTemplate = sMessageTemplate.getMsgContent();
            String title = sMessageTemplate.getMsgName();
            for (String id : suppilerIds) {
                SMessages sMessages = new SMessages();
                sMessages.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                sMessages.setBidSupplierId(id);
                sMessages.setUserIds(id);
                sMessages.setFlowFormId(formId);
                sMessages.setReadFlag(CommonConstants.NO_INTEGER);
                sMessages.setMsgType(MessagesMsgTypeEnum.MsgType8.getCode());
                sMessages.setMsgContent(MessageFormat.format(contentTemplate, wFlowForm1.getPurchaseItemName()));
                sMessages.setMsgTitle(MessageFormat.format(title, wFlowForm1.getPurchaseItemName()));
                sMessagesService.insert(sMessages);
            }
            WFlowForm wFlowForm = new WFlowForm();
            wFlowForm.setId(formId);
            wFlowForm.setSupplierReferersStatus(PurchaseCommonEnum.ASK_FILE_SEND_END.getCode());
            wFlowForm.setSupplierReferersSendTime(DateUtils.getNow());
            wFlowFormService.updateById(wFlowForm);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 二轮发标节点数据
     *
     * @param flowFormId
     * @return
     */
    @Override
    public List<ExtWFlowFormBackBid> sendBidTwoData(String flowFormId) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("formId", flowFormId);
        params.put("backBidOrNot", CommonConstants.YES_INTEGER);
        params.put("abandonedBidOrNot", CommonConstants.NO_INTEGER);
        params.put("qualificationOrNot", CommonConstants.YES_INTEGER);
        params.put("twoRound", AttachmentTypeEnum.ATTACHMENT_TYPE_41.getCode());
        return wFlowFormBackBidService.getExtBackBidByMap(params);
    }


    /**
     * 发标
     *
     * @param formId
     */
//	@Override
//	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
//	public void sendBidSubmit(String formId) {
//		try{
//			//更新发标后外网状态
//			sendBidDealToOuter(formId);
//
//			WFlowSubForm wFlowSubForm = new WFlowSubForm();
//			wFlowSubForm.setFlowFormId(formId);
//			wFlowSubForm.setSendBidStatus(CommonConstants.YES_INTEGER);
//			wFlowSubForm.setSendBidTime(DateUtils.getNow());
//			wFlowSubFormService.updateByFormId(wFlowSubForm);
//
//		}catch (Exception e){
//			e.printStackTrace();
//			throw new RuntimeException(e.getMessage(),e.getCause());
//		}
//	}
    @Override
    public TechnicalMarkScoreRspVO technicalMarkScoreDetail(String formId) {
        TechnicalMarkScoreRspVO technicalMarkScoreRspVO = new TechnicalMarkScoreRspVO();
        technicalMarkScoreRspVO.setFormId(formId);
        try {
            WFlowForm wFlowForm = wFlowFormService.selectById(formId);
            //PSpecialPurchasePlan pSpecialPurchasePlan=pSpecialPurchasePlanService.selectById(wFlowForm.getPurchasePlanId());
            technicalMarkScoreRspVO.setHandleUser(wFlowForm.getHandleUser());
            technicalMarkScoreRspVO.setHandleUserName(sysUserService.selectById(wFlowForm.getHandleUser()).getName());
            technicalMarkScoreRspVO.setPurchaseItemName(wFlowForm.getPurchaseItemName());

            technicalMarkScoreRspVO.setSn(wFlowForm.getSegmentsNumber());
            WFlowSubForm wFlowSubForm = wFlowSubFormService.selectByFormId(formId);
            if (wFlowForm != null)
                technicalMarkScoreRspVO.setTechnicalDidScoreTime(wFlowSubForm.getTechnicalBidScoreTime());

            Map<String, String> supplierIdAndDarkCode = new HashMap<>();
            Map<String, Object> params = new HashMap<>();
            params.put("formId", formId);
            params.put("bright", AttachmentTypeEnum.ATTACHMENT_TYPE_23.getCode());
            params.put("dark", AttachmentTypeEnum.ATTACHMENT_TYPE_24.getCode());
            params.put("backBidOrNot", CommonConstants.YES_INTEGER);
            params.put("order", "a.supplier_id,a.segments_number");
            List<ExtWFlowFormBackBid> extWFlowFormBackBids = wFlowFormBackBidService.getExtBackBidByMap(params);
            String supplierId = "";
            technicalMarkScoreRspVO.setBrightAttachs(Lists.newArrayList());
            technicalMarkScoreRspVO.setDarkAttachs(Lists.newArrayList());
            TechnicalMarkScoreAttach brightAttach = null;
            TechnicalMarkScoreAttach darkAttach = null;
            for (ExtWFlowFormBackBid extWFlowFormBackBid : extWFlowFormBackBids) {
                if (!supplierId.equals(extWFlowFormBackBid.getSupplierId())) {
                    brightAttach = new TechnicalMarkScoreAttach(extWFlowFormBackBid.getSupplierName());
                    darkAttach = new TechnicalMarkScoreAttach(extWFlowFormBackBid.getDarkBidCode());
                    technicalMarkScoreRspVO.getBrightAttachs().add(brightAttach);
                    technicalMarkScoreRspVO.getDarkAttachs().add(darkAttach);
                    supplierId = extWFlowFormBackBid.getSupplierId();
                    if (StringUtils.isNotEmpty(extWFlowFormBackBid.getDarkBidCode()))
                        supplierIdAndDarkCode.put(extWFlowFormBackBid.getSupplierId(), extWFlowFormBackBid.getDarkBidCode());
                }
                brightAttach.getAttachs().add(new TechnicalMarkScoreAttachDetail(
                        extWFlowFormBackBid.getSegmentsNumber(), extWFlowFormBackBid.getTechnicalBrightUrlName(), extWFlowFormBackBid.getTechnicalBrightUrl()));
                darkAttach.getAttachs().add(new TechnicalMarkScoreAttachDetail(
                        extWFlowFormBackBid.getSegmentsNumber(), extWFlowFormBackBid.getTechnicalDarkUrlName(), extWFlowFormBackBid.getTechnicalDarkUrl()));

            }
            if (CollectionUtils.isNotEmpty(technicalMarkScoreRspVO.getDarkAttachs())) {
                technicalMarkScoreRspVO.getDarkAttachs().sort((TechnicalMarkScoreAttach h1, TechnicalMarkScoreAttach h2) -> h1.getName().compareTo(h2.getName()));
            }

            List<List<ExtWFlowFormTechScoreDetals>> lstTechnicalBidBrightLs = new ArrayList<>();
            List<List<ExtWFlowFormTechScoreDetals>> lstTechnicalBidDarkLs = new ArrayList<>();
            List<List<ExtWFlowFormTechScoreDetals>> lstPMInterviewLs = new ArrayList<>();
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("flowFormId", formId);
            hashMap.put("userId", UserUtils.getCurrentUserId());
            //hashMap.put("userId","MG1930");
            List<ExtWFlowFormTechScoreDetals> lsSupplierIds = wFlowFormTechScoreDetalsService.getDitSupplierId(hashMap);
            for (ExtWFlowFormTechScoreDetals ext : lsSupplierIds) {
                hashMap.put("supplierId", ext.getSupplierId());

                hashMap.put("templateType", SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_BRIGHT_MARK.getCode() + "");
                List<ExtWFlowFormTechScoreDetals> lstTechnicalBidBright = wFlowFormTechScoreDetalsService.getList(hashMap);
                lstTechnicalBidBrightLs.add(lstTechnicalBidBright);

                hashMap.put("templateType", SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_DARK_MARK.getCode() + "");
                List<ExtWFlowFormTechScoreDetals> lstTechnicalBidDark = wFlowFormTechScoreDetalsService.getList(hashMap);
                if (CollectionUtils.isNotEmpty(lstTechnicalBidDark)) {
                    for (ExtWFlowFormTechScoreDetals extWFlowFormTechScoreDetals : lstTechnicalBidDark) {
                        extWFlowFormTechScoreDetals.setDarkBidCode(supplierIdAndDarkCode.get(extWFlowFormTechScoreDetals.getSupplierId()));
                    }
                    lstTechnicalBidDarkLs.add(lstTechnicalBidDark);
                }


                hashMap.put("templateType", SuppliersCategoryTemplateTypeEnum.SCORE_INTERVIEW_BY_MANAGER.getCode() + "");
                List<ExtWFlowFormTechScoreDetals> lstPMInterview = wFlowFormTechScoreDetalsService.getList(hashMap);
                lstPMInterviewLs.add(lstPMInterview);
            }

            technicalMarkScoreRspVO.setLstTechnicalBidBright(lstTechnicalBidBrightLs);

            if (CollectionUtils.isNotEmpty(lstTechnicalBidDarkLs)) {
                lstTechnicalBidDarkLs.sort((List<ExtWFlowFormTechScoreDetals> h1, List<ExtWFlowFormTechScoreDetals> h2) -> h1.get(0).getDarkBidCode().compareTo(h2.get(0).getDarkBidCode()));
            }
            technicalMarkScoreRspVO.setLstTechnicalBidDark(lstTechnicalBidDarkLs);

            technicalMarkScoreRspVO.setLstPMInterview(lstPMInterviewLs);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return technicalMarkScoreRspVO;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public boolean technicalMarkScoreSubmit(TechnicalMarkScoreRspVO technicalMarkScoreRspVO) {
        List<WFlowFormTechScoreDetals> ls = new ArrayList<>();
        try {
            String userId = UserUtils.getCurrentUserId();
            SMyDeals currentDeal = sMyDealsService.selectById(technicalMarkScoreRspVO.getDealId());
            if (currentDeal == null || currentDeal.getDoneFlag() == CommonConstants.YES_INTEGER) {
                throw new RuntimeException("代办已处理", new ServiceThrowable());
            }

            List<List<ExtWFlowFormTechScoreDetals>> lstTechnicalBidBright = technicalMarkScoreRspVO.getLstTechnicalBidBright();
//			List<WFlowFormIbTechScore> lsWFlowFormIbTechScore=new ArrayList<>();
            //String userId="MG10820";
            List<WFlowFormIbTechScore> lsWFlowFormIbTechScore = wFlowFormIbTechScoreService.selectList(new EntityWrapper<WFlowFormIbTechScore>()
                    .eq("flow_form_id", technicalMarkScoreRspVO.getFormId())
                    .eq("user_id", userId).eq("del_flag", CommonConstants.DEL_FLAG_NORMAL));
            for (List<ExtWFlowFormTechScoreDetals> extWFlowFormTechScoreDetals : lstTechnicalBidBright) {
                ls.addAll(ListObjCopyUtil.copyTo(extWFlowFormTechScoreDetals, WFlowFormTechScoreDetals.class));
//				WFlowFormIbTechScore wFlowFormIbTechScore=new WFlowFormIbTechScore();
//				wFlowFormIbTechScore.setUserId(userId);
//				wFlowFormIbTechScore.setBaseFeilds(userId,null,0,true);
                String supplierId = "";
                String flowFormId = "";
                Double bidBrightScore = 0D;
                for (ExtWFlowFormTechScoreDetals obj : extWFlowFormTechScoreDetals) {
                    supplierId = obj.getSupplierId();
                    flowFormId = obj.getFlowFormId();
                    bidBrightScore = bidBrightScore + obj.getScores();
                }
                for (WFlowFormIbTechScore wFlowFormIbTechScore : lsWFlowFormIbTechScore) {
                    if (flowFormId.equals(wFlowFormIbTechScore.getFlowFormId()) && supplierId.equals(wFlowFormIbTechScore.getSupplierId())) {
                        wFlowFormIbTechScore.setTechnicalScore(bidBrightScore);
                    }
                }
//				for(ExtWFlowFormTechScoreDetals obj:extWFlowFormTechScoreDetals){
//					wFlowFormIbTechScore.setFlowFormId(obj.getFlowFormId());
//					wFlowFormIbTechScore.setSupplierId(obj.getSupplierId());
//					bidBrightScore=bidBrightScore+obj.getScores();
//				}
//				wFlowFormIbTechScore.setTechnicalScore(bidBrightScore);
//				lsWFlowFormIbTechScore.add(wFlowFormIbTechScore);
            }

            List<List<ExtWFlowFormTechScoreDetals>> lstTechnicalBidDark = technicalMarkScoreRspVO.getLstTechnicalBidDark();
            for (List<ExtWFlowFormTechScoreDetals> extWFlowFormTechScoreDetals : lstTechnicalBidDark) {
                ls.addAll(ListObjCopyUtil.copyTo(extWFlowFormTechScoreDetals, WFlowFormTechScoreDetals.class));
                String supplierId = "";
                String flowFormId = "";
                Double bidDarkScore = 0D;
                for (ExtWFlowFormTechScoreDetals obj : extWFlowFormTechScoreDetals) {
                    supplierId = obj.getSupplierId();
                    flowFormId = obj.getFlowFormId();
                    bidDarkScore = bidDarkScore + obj.getScores();
                }
                for (WFlowFormIbTechScore wFlowFormIbTechScore : lsWFlowFormIbTechScore) {
                    if (flowFormId.equals(wFlowFormIbTechScore.getFlowFormId()) && supplierId.equals(wFlowFormIbTechScore.getSupplierId())) {
                        wFlowFormIbTechScore.setTechnicalDarkScore(bidDarkScore);
                    }
                }
            }

            List<List<ExtWFlowFormTechScoreDetals>> lstPMInterview = technicalMarkScoreRspVO.getLstPMInterview();
            for (List<ExtWFlowFormTechScoreDetals> extWFlowFormTechScoreDetals : lstPMInterview) {
                ls.addAll(ListObjCopyUtil.copyTo(extWFlowFormTechScoreDetals, WFlowFormTechScoreDetals.class));
                String supplierId = "";
                String flowFormId = "";
                Double pmInterviewScore = 0D;
                for (ExtWFlowFormTechScoreDetals obj : extWFlowFormTechScoreDetals) {
                    supplierId = obj.getSupplierId();
                    flowFormId = obj.getFlowFormId();
                    pmInterviewScore = pmInterviewScore + obj.getScores();
                }
                for (WFlowFormIbTechScore wFlowFormIbTechScore : lsWFlowFormIbTechScore) {
                    if (flowFormId.equals(wFlowFormIbTechScore.getFlowFormId()) && supplierId.equals(wFlowFormIbTechScore.getSupplierId())) {
                        wFlowFormIbTechScore.setPmInterviewScore(pmInterviewScore);
                    }
                }
            }

            if (ls != null && ls.size() > 0) {
                wFlowFormTechScoreDetalsService.updateBatchById(ls);
            }
            if (lsWFlowFormIbTechScore != null && lsWFlowFormIbTechScore.size() > 0) {
//				wFlowFormIbTechScoreService.insertBatch(lsWFlowFormIbTechScore);
                wFlowFormIbTechScoreService.updateBatchById(lsWFlowFormIbTechScore);
            }

            Date now = new Date();
            //更新待办
            List<SMyDeals> lstSMyDeals = sMyDealsService.selectList(
                    new EntityWrapper<SMyDeals>(new SMyDeals().
                            setActionType(MyDealActionTypeEnum.INQUIRING_BID_SCORE.getCode())
                            .setRelatedId(technicalMarkScoreRspVO.getFormId())
                            .setDoneFlag(CommonConstants.UNDONG_FLAG)
                    ));
            //判断是否最后一个人打分   是否打分完成
            boolean complete = true;
            if (lstSMyDeals != null && lstSMyDeals.size() > 0) {
                for (SMyDeals sMyDeals : lstSMyDeals) {
                    if (userId.equals(sMyDeals.getUserId())) {
                        sMyDeals.setBaseFeilds(userId, null, 0, false);
                        sMyDeals.setDoneFlag(CommonConstants.DONG_FLAG);
                        sMyDeals.setDealDoneTime(now);
                        sMyDealsService.updateById(sMyDeals);
                    } else {
                        complete = false;
                    }
                }
            }
            //打分完成 更新w_flow_sub_form
            if (complete) {
                WFlowSubForm wFlowSubForm = wFlowSubFormService.selectByFormId(technicalMarkScoreRspVO.getFormId());
                wFlowSubForm.setTechnicalBidScoreDoneFlag(CommonConstants.YES_INTEGER);
                wFlowSubForm.setTechnicalBidScoreDoneTime(now);
                wFlowSubForm.setBaseFeilds(userId, null, 0, false);
                wFlowSubFormService.updateById(wFlowSubForm);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
        return true;
    }


    /**
     * 流标
     *
     * @param formId
     * @return
     */

    @Override
    public FlowBidRspVO flowBid(String formId) {
        FlowBidRspVO flowBidRspVO = new FlowBidRspVO();
        WFlowForm wFlowForm = wFlowFormService.selectById(formId);

        flowBidRspVO.setFlowForm(wFlowForm);
        flowBidRspVO.setHandleUserName(sysUserService.selectById(wFlowForm.getHandleUser()).getName());
        flowBidRspVO.setShistoryComments(sHistoryCommentService.findExtByModelTypeAndRelatedId(HistoryCommentModelTypeEnum.HistoryCommentModelType13.getCode(), formId, null));
        return flowBidRspVO;
    }


    /**
     * 提交二轮发标
     *
     * @param vo
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void sendBidTwoSubmit(SendBidTwoReqVO vo) {
        try {
//			Map<String,Object> params= Maps.newHashMap();
//			params.put("formId",vo.getFormId());
//			params.put("backBidOrNot",CommonConstants.YES_INTEGER);
//			params.put("abandonedBidOrNot",CommonConstants.NO_INTEGER);
//			params.put("qualificationOrNot",CommonConstants.YES_INTEGER);
//			List<ExtWFlowFormBackBid> wFlowFormBackBids = wFlowFormBackBidService.getExtBackBidByMap(params);

            List<WFlowFormBackBid> wFlowFormBackBids = wFlowFormBackBidService.getByIds(vo.getIds());
            Set<String> supplierIds = new HashSet<>();
            WFlowFormBackBid wFlowFormBackBidUpdate = new WFlowFormBackBid();
            wFlowFormBackBidUpdate.setRoundTwoFlag(CommonConstants.YES_INTEGER);
            for (WFlowFormBackBid wFlowFormBackBid : wFlowFormBackBids) {
                wFlowFormBackBidUpdate.setId(wFlowFormBackBid.getId());
                supplierIds.add(wFlowFormBackBid.getSupplierId());
                WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(vo.getFormId(), wFlowFormBackBid.getSupplierId());
                WFlowFormExtSubMng wFlowFormExtSubMng = wFlowFormExtSubMngService.updateByParentIdAndSn(WFlowFormExtSubEnum.STATUS_4_6.getCode(), wFlowFormExtMng.getId(), wFlowFormBackBid.getSegmentsNumber());
                SHistoryComment sHistoryComment = buildCommonHistory(vo.getFormId(), wFlowFormExtSubMng.getId(),
                        HistoryCommentModelTypeEnum.HistoryCommentModelType25.getCode(), "",
                        PurchaseActionNameEnum.PURCHASE_PLAN_7_2.getDesc(), PurchaseNodeEnum.NODE_7_2.getDesc(),
                        0, false);
                sHistoryComment.setActionStatus(PurchaseCommonEnum.OUTER_PROCESS_STATUS_1.getCode());
                sHistoryCommentService.insert(sHistoryComment);

                wFlowFormBackBidService.updateById(wFlowFormBackBidUpdate);

            }


            //List<ExtWFlowFormBackBid> extWFlowFormBackBids = wFlowFormBackBidService.getExtBackBidByMap(params);
//			for(ExtWFlowFormBackBid extWFlowFormBackBid:extWFlowFormBackBids){
////				if(supplierTem.get(extWFlowFormBackBid.getSupplierId())==null){
////					supplierTem.put(extWFlowFormBackBid.getSupplierId(),extWFlowFormBackBid.getSupplierId());
////					sMyDealsService.insert(buildCommonDeals(vo.getFormId(),vo.getFormId(),
////							MyDealSubTypeEnum.TWO_RETURN_BID.getCode(),
////							MyDealActionTypeEnum.BIDS_DOWN_TWO_OUT.getCode(),
////							CommentConfigEnum.BIDS_DOWN_ADD_DEAL.getCode(),
////							extWFlowFormBackBid.getSupplierId(), true,null));
////				}
//				suppliers.add(extWFlowFormBackBid.getSupplierId());
//				WFlowFormSendBid wFlowFormSendBid = new WFlowFormSendBid();
//				wFlowFormSendBid.setBaseFeilds(UserUtils.getCurrentUserId(),"",CommonConstants.NO_INTEGER,true);
//				wFlowFormSendBid.setDownloadOrNot(CommonConstants.NO_INTEGER);
//				wFlowFormSendBid.setFlowFormId(vo.getFormId());
//				wFlowFormSendBid.setSupplierId(extWFlowFormBackBid.getSupplierId());
//				wFlowFormSendBid.setSegmentsNumber(extWFlowFormBackBid.getSegmentsNumber());
//				wFlowFormSendBidService.insert(wFlowFormSendBid);
//			}
            sendBackBidDeal(vo.getFormId(), wFlowFormBackBids, 2, vo.getDelayTime());
            //
            // updateBackBidInvalid(wFlowForm,2);

            WFlowSubForm wFlowSubForm = new WFlowSubForm();
            wFlowSubForm.setFlowFormId(vo.getFormId());
            wFlowSubForm.setSendBidReturnStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_9_STATUS_2.getCode());
            wFlowSubForm.setSendBidReturnTime(DateUtils.getNow());
            wFlowSubFormService.updateByFormId(wFlowSubForm);

            WFlowFormTimeNode wFlowFormTimeNode = new WFlowFormTimeNode();
            wFlowFormTimeNode.setFlowFormId(vo.getFormId());
            wFlowFormTimeNode.setTwoRoundBackBid(vo.getDelayTime());
            wFlowFormTimeNodeService.updateByFormId(wFlowFormTimeNode);
            LicenseUtil.INSTANCE.validate();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }


    /**
     * 发起商务谈判
     *
     * @param businessBidReqVO
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void initiateBusinessNegotiations(BusinessBidReqVO businessBidReqVO) {
        try {
            List<WFlowFormBackBid> wFlowFormBackBids = wFlowFormBackBidService.getByIds(StringUtils.getListBySplitStr(businessBidReqVO.getIds()));
            Set<String> supplierIds = new HashSet<>();
            WFlowFormBackBid wFlowFormBackBidUpdate = new WFlowFormBackBid();
            wFlowFormBackBidUpdate.setBusinessNegotiationFlag(CommonConstants.YES_INTEGER);
            for (WFlowFormBackBid wFlowFormBackBid : wFlowFormBackBids) {
                wFlowFormBackBidUpdate.setId(wFlowFormBackBid.getId());
                supplierIds.add(wFlowFormBackBid.getSupplierId());
                WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(businessBidReqVO.getFormId(), wFlowFormBackBid.getSupplierId());
                wFlowFormExtSubMngService.updateByParentIdAndSn(WFlowFormExtSubEnum.STATUS_4_8.getCode(), wFlowFormExtMng.getId(), wFlowFormBackBid.getSegmentsNumber());
                wFlowFormBackBidService.updateById(wFlowFormBackBidUpdate);
            }

            LicenseUtil.INSTANCE.validate();
            sendBackBidDeal(businessBidReqVO.getFormId(), wFlowFormBackBids, 3, businessBidReqVO.getDelayTime());

            WFlowSubForm wFlowSubForm = new WFlowSubForm();
            wFlowSubForm.setFlowFormId(businessBidReqVO.getFormId());
            wFlowSubForm.setBusinessNegotiationStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_10_STATUS_2.getCode());
            wFlowSubForm.setBusinessNegotiationTime(DateUtils.getNow());
            wFlowSubFormService.updateByFormId(wFlowSubForm);

            WFlowFormTimeNode wFlowFormTimeNode = new WFlowFormTimeNode();
            wFlowFormTimeNode.setFlowFormId(businessBidReqVO.getFormId());
            wFlowFormTimeNode.setBusinessNegoteReturn(businessBidReqVO.getDelayTime());
            wFlowFormTimeNodeService.updateByFormId(wFlowFormTimeNode);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 评标节点数据
     *
     * @param flowFormId
     * @return
     */
    @Override
    public BidEvaluationConclusionRspVO getBidEvaluationConclusion(String flowFormId) {
        BidEvaluationConclusionRspVO bidEvaluationConclusionRspVO = new BidEvaluationConclusionRspVO();
        Map<String, Object> params = Maps.newHashMap();
        LicenseUtil.INSTANCE.validate();
        WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(flowFormId);
        params.put("formId", flowFormId);
        params.put("business", AttachmentTypeEnum.ATTACHMENT_TYPE_40.getCode());
        bidEvaluationConclusionRspVO.setTimeFlag(isTime(wFlowFormTimeNode.getBidEvaluation(), wFlowFormTimeNode.getBidEvaluationDelay()));
        bidEvaluationConclusionRspVO.setCalibrationInfoRspVOS(backBidInfoFormat(wFlowFormBackBidService.getExtBackBidByMap(params)));
        bidEvaluationConclusionRspVO.setBidEvaluationConclusion(wFlowFormService.selectById(flowFormId).getBidEvaluationConclusion());
        bidEvaluationConclusionRspVO.setDelayTime(wFlowFormTimeNode.getBidEvaluation());
        bidEvaluationConclusionRspVO.setExtensionDelayTime(wFlowFormTimeNode.getBidEvaluationDelay());
        bidEvaluationConclusionRspVO.setComprehensiveAttachs(sAttachmentService.getByFormIdAndAttachmentType(flowFormId, AttachmentTypeEnum.ATTACHMENT_TYPE_29.getCode(), null));
        bidEvaluationConclusionRspVO.setOtherAttachs(sAttachmentService.getByFormIdAndAttachmentType(flowFormId, AttachmentTypeEnum.ATTACHMENT_TYPE_30.getCode(), null));
        return bidEvaluationConclusionRspVO;
    }

    /**
     * 评标约谈节点数据
     *
     * @param flowFormId
     * @return
     */
    @Override
    public BidEvaluationInterviewRspVO bidEvaluationInterviewData(String flowFormId) {

        WFlowForm wFlowForm = wFlowFormService.selectById(flowFormId);
        WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(flowFormId);
        BidEvaluationInterviewRspVO bidEvaluationInterviewReqVO = new BidEvaluationInterviewRspVO();
        bidEvaluationInterviewReqVO.setBackBidRound(wFlowForm.getBackBidRounds());
        bidEvaluationInterviewReqVO.setCalibrationPrinciple(wFlowForm.getCalibrationPrinciple());
        bidEvaluationInterviewReqVO.setDelayTime(wFlowFormTimeNode.getBidEvaluation());
        LicenseUtil.INSTANCE.validate();
        Map<String, Object> params = Maps.newHashMap();
        params.put("formId", flowFormId);
        params.put("backBidOrNot", CommonConstants.YES_INTEGER);
        params.put("abandonedBidOrNot", CommonConstants.NO_INTEGER);
        params.put("qualificationOrNot", CommonConstants.YES_INTEGER);
        bidEvaluationInterviewReqVO.setLists(wFlowFormBackBidService.getExtBackBidByMap(params));
        return bidEvaluationInterviewReqVO;
    }

    @Override
    public BidEvaluationInterviewRspVO initiateBusinessNegotiationsData(String flowFormId) {
        WFlowForm wFlowForm = wFlowFormService.selectById(flowFormId);
        BidEvaluationInterviewRspVO bidEvaluationInterviewReqVO = new BidEvaluationInterviewRspVO();
        bidEvaluationInterviewReqVO.setBackBidRound(wFlowForm.getBackBidRounds());
        Map<String, Object> params = Maps.newHashMap();
        params.put("formId", flowFormId);
        params.put("backBidOrNot", CommonConstants.YES_INTEGER);
        params.put("abandonedBidOrNot", CommonConstants.NO_INTEGER);
        params.put("qualificationOrNot", CommonConstants.YES_INTEGER);
        bidEvaluationInterviewReqVO.setLists(wFlowFormBackBidService.getExtBackBidByMap(params));
        return bidEvaluationInterviewReqVO;
    }

    /**
     * 提交评标约谈
     *
     * @param vo
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void bidEvaluationInterviewSubmit(BidEvaluationInterviewReqVO vo) {
        try {
            List<WFlowFormBackBid> wFlowFormBackBids = wFlowFormBackBidService.getByIds(StringUtils.getListBySplitStr(vo.getIds()));
            Set<String> supplierIds = new HashSet<>();
            WFlowFormBackBid wFlowFormBackBidUpdate = new WFlowFormBackBid();
            wFlowFormBackBidUpdate.setBidEvaluationFlag(CommonConstants.YES_INTEGER);
            for (WFlowFormBackBid wFlowFormBackBid : wFlowFormBackBids) {
                wFlowFormBackBidUpdate.setId(wFlowFormBackBid.getId());
                supplierIds.add(wFlowFormBackBid.getSupplierId());
                WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(vo.getFormId(), wFlowFormBackBid.getSupplierId());
                wFlowFormExtSubMngService.updateByParentIdAndSn(WFlowFormExtSubEnum.STATUS_4_10.getCode(), wFlowFormExtMng.getId(), wFlowFormBackBid.getSegmentsNumber());
                wFlowFormBackBidService.updateById(wFlowFormBackBidUpdate);
            }

            LicenseUtil.INSTANCE.validate();

            sendBackBidDeal(vo.getFormId(), wFlowFormBackBids, 4, vo.getDelayTime());
            WFlowSubForm wFlowSubForm = new WFlowSubForm();
            wFlowSubForm.setFlowFormId(vo.getFormId());
            wFlowSubForm.setBidEvaluationStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_11_STATUS_2.getCode());
            wFlowSubForm.setBidEvaluationTime(DateUtils.getNow());
            wFlowSubFormService.updateByFormId(wFlowSubForm);

            WFlowFormTimeNode wFlowFormTimeNode = new WFlowFormTimeNode();
            wFlowFormTimeNode.setFlowFormId(vo.getFormId());
            wFlowFormTimeNode.setBidEvaluation(vo.getDelayTime());
            wFlowFormTimeNodeService.updateByFormId(wFlowFormTimeNode);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }


    /**
     * 定标节点数据
     *
     * @param wflowFormId
     * @return
     */
    @Override
    public ConfirmBidNodeAllDataResVO selectConfirmBidNodeData(String wflowFormId) {
        ConfirmBidNodeAllDataResVO confirmBidNodeAllDataResVO = new ConfirmBidNodeAllDataResVO();

        confirmBidNodeAllDataResVO.setSattachments(sAttachmentService.getByFormIdAndAttachmentType(wflowFormId,
                AttachmentTypeEnum.ATTACHMENT_TYPE_31.getCode(), null));

        confirmBidNodeAllDataResVO.setSattachments1(sAttachmentService.getByFormIdAndAttachmentType(wflowFormId,
                AttachmentTypeEnum.ATTACHMENT_TYPE_47.getCode(), null));
        confirmBidNodeAllDataResVO.setSattachments4(sAttachmentService.getByFormIdAndAttachmentType(wflowFormId,
                AttachmentTypeEnum.ATTACHMENT_TYPE_50.getCode(), null));
        confirmBidNodeAllDataResVO.setSattachments7(sAttachmentService.getByFormIdAndAttachmentType(wflowFormId,
                AttachmentTypeEnum.ATTACHMENT_TYPE_53.getCode(), null));
        confirmBidNodeAllDataResVO.setSattachments9(sAttachmentService.getByFormIdAndAttachmentType(wflowFormId,
                AttachmentTypeEnum.ATTACHMENT_TYPE_55.getCode(), null));
//		confirmBidNodeAllDataResVO.setSattachments10(sAttachmentService.getByFormIdAndAttachmentType(wflowFormId,
//				AttachmentTypeEnum.ATTACHMENT_TYPE_56.getCode(), null));

        confirmBidNodeAllDataResVO.setExtWFlowFormDiscussionHistories(wFlowFormDiscussionHistoryService.getExtByFormIdAndType(wflowFormId, null));
        WFlowForm wFlowForm = wFlowFormService.selectById(wflowFormId);
        Integer flowType = wFlowForm.getFlowType();
        if (flowType == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_5.getCode()) {
            confirmBidNodeAllDataResVO.setWflowFormStrategicProtocols(wlowFormStrategicProtocolService.getByFormId(wflowFormId));
            confirmBidNodeAllDataResVO.setExtWFlowFormBidCandidateUnits(
                    wFlowFormBidCandidateUnitService.getAwardBidByFormId(wflowFormId));
        } else {
            confirmBidNodeAllDataResVO.setSattachments2(sAttachmentService.getByFormIdAndAttachmentType(wflowFormId,
                    AttachmentTypeEnum.ATTACHMENT_TYPE_48.getCode(), null));
            confirmBidNodeAllDataResVO.setSattachments3(sAttachmentService.getByFormIdAndAttachmentType(wflowFormId,
                    AttachmentTypeEnum.ATTACHMENT_TYPE_49.getCode(), null));
            confirmBidNodeAllDataResVO.setSattachments5(sAttachmentService.getByFormIdAndAttachmentType(wflowFormId,
                    AttachmentTypeEnum.ATTACHMENT_TYPE_51.getCode(), null));
            confirmBidNodeAllDataResVO.setSattachments6(sAttachmentService.getByFormIdAndAttachmentType(wflowFormId,
                    AttachmentTypeEnum.ATTACHMENT_TYPE_52.getCode(), null));
            confirmBidNodeAllDataResVO.setSattachments8(sAttachmentService.getByFormIdAndAttachmentType(wflowFormId,
                    AttachmentTypeEnum.ATTACHMENT_TYPE_54.getCode(), null));
        }
        Map<String, Object> param = Maps.newHashMap();
        if (flowType != PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_4.getCode() &&
                flowType != PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_5.getCode() &&
                flowType != PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_6.getCode()) {
            //param.put("backBidOrNot",CommonConstants.YES_INTEGER);
            param.put("dingBid", AttachmentTypeEnum.ATTACHMENT_TYPE_42.getCode());
        }

        LicenseUtil.INSTANCE.validate();
        param.put("formId", wflowFormId);

        if (flowType == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_4.getCode()) {
            param.put("bright", AttachmentTypeEnum.ATTACHMENT_TYPE_23.getCode());
            param.put("business", AttachmentTypeEnum.ATTACHMENT_TYPE_25.getCode());
        }
        confirmBidNodeAllDataResVO.setCalibrationInfoRspVOS(backBidInfoFormat(wFlowFormBackBidService.getExtBackBidByMap(param)));

        confirmBidNodeAllDataResVO.setShistoryComments(sHistoryCommentService.findExtByModelTypeAndRelatedId(
                HistoryCommentModelTypeEnum.HistoryCommentModelType11.getCode(), wflowFormId, wflowFormId));
        return confirmBidNodeAllDataResVO;
    }

    /**
     * 定标约谈页面数据
     *
     * @param formId
     * @return
     */
    @Override
    public List<CalibrationInfoRspVO> selectCalibrationInterviewData(String formId) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("formId", formId);
        LicenseUtil.INSTANCE.validate();
        params.put("backBidOrNot", CommonConstants.YES_INTEGER);
        params.put("abandonedBidOrNot", CommonConstants.NO_INTEGER);
        params.put("qualificationOrNot", CommonConstants.YES_INTEGER);
        params.put("dingBid", AttachmentTypeEnum.ATTACHMENT_TYPE_42.getCode());
        List<ExtWFlowFormBackBid> extWFlowFormBackBids = wFlowFormBackBidService.getExtBackBidByMap(params);

        return backBidInfoFormat(extWFlowFormBackBids);
    }


    /**
     * 删除引用的战略协议
     *
     * @param id
     */
    @Override
    public void deleteQuoteStrategicProtocol(String id) {
        wlowFormStrategicProtocolService.deleteById(id);
    }

    @Override
    public void updatePriceQuoteStrategicProtocol(String id, Double price) {
        wlowFormStrategicProtocolService.updatePriceById(id, price);
    }

    /**
     * 战略协议列表
     *
     * @param wStrategicProtocolReqVO
     * @return
     */
    @Override
    public List<ExtWStrategicProtocol> getQuoteStrategicProtocolList(WStrategicProtocolReqVO wStrategicProtocolReqVO) {
        ExtWStrategicProtocol wStrategicProtocol = new ExtWStrategicProtocol();
//		WFlowForm wFlowForm = wFlowFormService.selectById(wStrategicProtocolReqVO.getFormId());
//		wStrategicProtocol.setRegionalCompanyId(wFlowForm.getRegionalCompanyId());
        wStrategicProtocol.setStrategicStatus(CommonConstants.YES_INTEGER);
        wStrategicProtocol.setSupplierName(wStrategicProtocolReqVO.getSupplierName());
        wStrategicProtocol.setStrategicName(wStrategicProtocolReqVO.getProtocolName());
        wStrategicProtocol.setStrategicCategoryName(wStrategicProtocolReqVO.getStrategicCategoryName());
        return wStrategicProtocolService.findByEntity(wStrategicProtocol);
    }

    @Override
    public void getQuoteStrategicProtocolPage(Page<ExtWStrategicProtocol> page, WStrategicProtocolReqVO wStrategicProtocolReqVO) {
        ExtWStrategicProtocol wStrategicProtocol = new ExtWStrategicProtocol();
//		WFlowForm wFlowForm = wFlowFormService.selectById(wStrategicProtocolReqVO.getFormId());
//		wStrategicProtocol.setRegionalCompanyId(wFlowForm.getRegionalCompanyId());
        wStrategicProtocol.setStrategicStatus(CommonConstants.YES_INTEGER);
        LicenseUtil.INSTANCE.validate();
        wStrategicProtocol.setSupplierName(wStrategicProtocolReqVO.getSupplierName());
        wStrategicProtocol.setStrategicName(wStrategicProtocolReqVO.getProtocolName());
        wStrategicProtocol.setRegionalCompanyId(wStrategicProtocolReqVO.getRegionalCompanyId());
        wStrategicProtocol.setStrategicCategoryId(wStrategicProtocolReqVO.getStrategicCategoryId());
        wStrategicProtocol.setStrategicCategoryName(wStrategicProtocolReqVO.getStrategicCategoryName());
        wStrategicProtocol.setProtocolStartTime(wStrategicProtocolReqVO.getProtocolStartTime());
        wStrategicProtocol.setProtocolEndTime(wStrategicProtocolReqVO.getProtocolEndTime());
        page.setRecords(wStrategicProtocolService.findPageByEntity(page, wStrategicProtocol));
    }

    /**
     * 删除投标候选
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public WFlowFormBidCandidateUnit deleteBidCandidateUnit(String id) {
        WFlowFormBidCandidateUnit wFlowFormBidCandidateUnit = wFlowFormBidCandidateUnitService.selectById(id);
        wFlowFormBidCandidateUnit.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.YES_INTEGER, false);
        if (wFlowFormBidCandidateUnit.getCandidateType() == PurchaseCommonEnum.CANDIDATE_TYPE_IN.getCode()) {
            CalibrationInfoReqVO calibrationInfoReqVO = new CalibrationInfoReqVO();
            calibrationInfoReqVO.setFlowFormId(wFlowFormBidCandidateUnit.getFlowFormId());
            calibrationInfoReqVO.setSupplierId(wFlowFormBidCandidateUnit.getSuppliersId());
            wFlowFormBackBidService.deleteByformIdOrSupplierId(calibrationInfoReqVO);
            updatecalibrationStatus(wFlowFormBidCandidateUnit.getFlowFormId(), PurchaseNodeButtonStatusEnum.PURCHASE_NODE_12_STATUS_1.getCode());
        }
        wFlowFormBidCandidateUnitService.updateById(wFlowFormBidCandidateUnit);
        return wFlowFormBidCandidateUnit;
    }

    /**
     * 新增中投标候选人
     *
     * @param bidCandidateUnitRequestVO
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public ExtWFlowFormBidCandidateUnit addBidCandidateUnit(BidCandidateUnitReqResVO bidCandidateUnitRequestVO) {

        WFlowFormBidCandidateUnit wFlowFormBidCandidateUnit = new WFlowFormBidCandidateUnit();
        wFlowFormBidCandidateUnit.setFlowFormId(bidCandidateUnitRequestVO.getFlowFormId());
        wFlowFormBidCandidateUnit.setCandidateType(bidCandidateUnitRequestVO.getCandidateType());
        wFlowFormBidCandidateUnit.setSuppliersId(bidCandidateUnitRequestVO.getSuppliersId());
        wFlowFormBidCandidateUnit.setSuppliersRank(bidCandidateUnitRequestVO.getSuppliersRank());
        wFlowFormBidCandidateUnit.setQualificationGrade(bidCandidateUnitRequestVO.getQualificationGrade());
        wFlowFormBidCandidateUnit.setSuppliersSource(bidCandidateUnitRequestVO.getSuppliersSource());
        wFlowFormBidCandidateUnit.setSupplierSourceInfo(bidCandidateUnitRequestVO.getSupplierSourceInfo());
        wFlowFormBidCandidateUnit.setMainContactName(bidCandidateUnitRequestVO.getMainContactName());
        wFlowFormBidCandidateUnit.setMainContactMobile(bidCandidateUnitRequestVO.getMainContactMobile());
        wFlowFormBidCandidateUnit.setMainContactPosition(bidCandidateUnitRequestVO.getMainContactPosition());
        wFlowFormBidCandidateUnit.setManagementModel(bidCandidateUnitRequestVO.getManagementModel());
        wFlowFormBidCandidateUnit.setInnerAchives(bidCandidateUnitRequestVO.getInnerAchives());
        wFlowFormBidCandidateUnit.setOuterAchives(bidCandidateUnitRequestVO.getOuterAchives());
        wFlowFormBidCandidateUnit.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);
        if (bidCandidateUnitRequestVO.getCandidateType() == PurchaseCommonEnum.CANDIDATE_TYPE_IN.getCode()) {
            WFlowForm wFlowForm = wFlowFormService.selectById(bidCandidateUnitRequestVO.getFlowFormId());
            int sn = wFlowForm.getSegmentsNumber() == null ? 1 : wFlowForm.getSegmentsNumber();
            for (int i = 1; i <= sn; i++) {
                WFlowFormBackBid wFlowFormBackBid = buildWFlowFormBackBid(wFlowForm.getId(), bidCandidateUnitRequestVO.getSuppliersId(),
                        CommonConstants.AWARD_BID, CommonConstants.BID_OK, i);
                wFlowFormBackBidService.insert(wFlowFormBackBid);
            }
            updatecalibrationStatus(wFlowFormBidCandidateUnit.getFlowFormId(), PurchaseNodeButtonStatusEnum.PURCHASE_NODE_12_STATUS_2.getCode());
        }
        wFlowFormBidCandidateUnit = wFlowFormBidCandidateUnitService.add(wFlowFormBidCandidateUnit);
        ExtWFlowFormBidCandidateUnit extWFlowFormBidCandidateUnit = new ExtWFlowFormBidCandidateUnit();
        BeanUtils.copyProperties(wFlowFormBidCandidateUnit, extWFlowFormBidCandidateUnit);
        extWFlowFormBidCandidateUnit.setSuppliersName(sSuppliersService.getById(extWFlowFormBidCandidateUnit.getSuppliersId()).getCompanyName());
        return extWFlowFormBidCandidateUnit;
    }

    /**
     * 获取回标的供应商id和名字
     *
     * @param formId
     * @return
     */
    @Override
    public List<IdName> selectAddInquiringBidAnswerData(String formId) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("formId", formId);
        params.put("backBidOrNot", CommonConstants.YES_INTEGER);
        return wFlowFormBackBidService.selectIdAndNameByMap(params);
    }


    /**
     * 定标约谈
     *
     * @param vo
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void calibrationInterview(CalibrationInterviewVO vo) {
        try {
            WFlowFormBackBid wFlowFormBackBid = wFlowFormBackBidService.selectOneByFormIdAndSupplierIdAndSn(
                    vo.getFlowFormId(), vo.getSupplierId(), vo.getSegmentsNumber());
            BeanUtils.copyProperties(vo, wFlowFormBackBid);
            wFlowFormBackBidService.updateById(wFlowFormBackBid);

            SAttachment where = new SAttachment();
            where.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_42.getCode());
            where.setRelatedId(wFlowFormBackBid.getId());
            where.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
            SAttachment sAttachment = sAttachmentService.getOneByEntity(where);
            if (sAttachment == null) {
                vo.getAttachment().setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_42.getCode());
                vo.getAttachment().setAttachmentSubType(AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                vo.getAttachment().setRelatedId(wFlowFormBackBid.getId());
                vo.getAttachment().setFormId(vo.getFlowFormId());
                vo.getAttachment().setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                sAttachmentService.insert(vo.getAttachment());
            } else {
                if (StringUtils.isEmpty(vo.getAttachment().getAttachPath())) {
                    sAttachmentService.deleteById(sAttachment.getId());
                } else {
                    BeanUtils.copyProperties(vo.getAttachment(), sAttachment, getNullPropertyNames(vo.getAttachment()));
                    sAttachmentService.updateById(sAttachment);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }

    /**
     * 选择中标单位
     *
     * @param selectBidUnitReqVo
     * @return RestReturnResult
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void selectBidUnit(SelectBidUnitReqVo selectBidUnitReqVo) {
        try {
            if (selectBidUnitReqVo.getFlowFormId() != null) {
                WFlowFormBackBid w = new WFlowFormBackBid();
                w.setAwardBidOrNot(CommonConstants.AWARD_BID_NOT);
                wFlowFormBackBidService.update(w, new EntityWrapper<WFlowFormBackBid>()
                        .eq("flow_form_id", selectBidUnitReqVo.getFlowFormId()));
            }
            for (String id : selectBidUnitReqVo.getIds().split(",")) {
                WFlowFormBackBid ww = new WFlowFormBackBid();
                ww.setId(id);
                ww.setAwardBidOrNot(CommonConstants.AWARD_BID);
                ww.setUpdateDate(DateUtils.getNow());
                wFlowFormBackBidService.updateById(ww);
            }

            LicenseUtil.INSTANCE.validate();
            updatecalibrationStatus(selectBidUnitReqVo.getFlowFormId(), PurchaseNodeButtonStatusEnum.PURCHASE_NODE_12_STATUS_2.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 发起定标审批
     *
     * @param calibrationApprovalVO
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public RestReturnResult launchCalibrationApproval(CalibrationApprovalVO calibrationApprovalVO) {
        try {
            //sendBpm(calibrationApprovalVO.getFormId(),calibrationApprovalVO.getFormId(),AbutmentSubTypeEnum.LINE_STATUS_CALIBRATION_BID.getCode());
            WFlowSubForm wsf = wFlowSubFormService.selectByFormId(calibrationApprovalVO.getFormId());
            if (wsf.getCalibrationBidStatus() >= PurchaseNodeButtonStatusEnum.PURCHASE_NODE_12_STATUS_3.getCode()) {
                throw new RuntimeException("不允许重复发起审批！！！", new ServiceThrowable());
            }

            RestReturnResult restResult = RestReturnResult.success();
            WFlowForm wFlowForm = wFlowFormService.selectById(calibrationApprovalVO.getFormId());
            /*
            if (wFlowForm.getPurchasePlanType() == PurchaseCommonEnum.PURCHASE_PLAN_TYPE_SPECIAL.getCode()) {

                if (StringUtils.isNotEmpty(wFlowForm.getContractCode()) && "true".equalsIgnoreCase(synDataService.querySourcingStatus(wFlowForm.getContractCode()))) {
                    restResult = RestReturnResult.error();
                    restResult.setSystemCode(CommonConstants.ERROR_CONTACT_STATUS_FAIL);
                    return restResult;
                }else{
                    throw new RuntimeException("不允许重复发起审批！！！", new ServiceThrowable());
                }
            }*/
            if (wFlowForm.getPurchasePlanType() == PurchaseCommonEnum.PURCHASE_PLAN_TYPE_SPECIAL.getCode()) {
                if (StringUtils.isEmpty(wFlowForm.getContractId())) {
                    throw new RuntimeException("请关联合约规划！！！", new ServiceThrowable());
                }
            }

            Map<String, Object> result = sendBpmCalibrationBid(wFlowFormService.selectById(calibrationApprovalVO.getFormId()));
            String bpmUrl = String.valueOf(result.get("BPM_URL"));
            String nodeName = sCommentConfigService.getValueByCode(CommentConfigEnum.P_DINGBID_NODE_NAME_HISTORY_LAUNCH.getCode());
            SHistoryComment historyComment = buildCommonHistory(calibrationApprovalVO.getFormId(), calibrationApprovalVO.getFormId(),
                    HistoryCommentModelTypeEnum.HistoryCommentModelType11.getCode(), "",
                    PurchaseActionNameEnum.PURCHASE_PLAN_4_1.getDesc(), nodeName, 0, false);
            historyComment.setCommentUrl(bpmUrl);
            sHistoryCommentService.saveSHistoryComment(historyComment);
            updateWfformMbsStatus(calibrationApprovalVO.getFormId(), WFlowFormStatusEnum.MBS_BPM_FLAG_2.getCode());
            updatecalibrationStatus(calibrationApprovalVO.getFormId(), PurchaseNodeButtonStatusEnum.PURCHASE_NODE_12_STATUS_3.getCode());

            LicenseUtil.INSTANCE.validate();
            wFlowForm = new WFlowForm();
            wFlowForm.setId(calibrationApprovalVO.getFormId());
            wFlowForm.setCalibrationConclusion(calibrationApprovalVO.getConfirmBidConclusion());
            wFlowFormService.updateById(wFlowForm);
            return restResult;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 发送中标通知书和感谢信
     *
     * @param formId
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void sendNoticeAndThank(String formId) {
        try {
            WFlowForm wFlowForm = wFlowFormService.selectById(formId);
            SMessageTemplate sMessageTemplate = sMessageTemplateService.getByMsgType(MessagesMsgTypeEnum.MsgType12.getCode());
            SMessageTemplate sMessageTemplate1 = sMessageTemplateService.getByMsgType(MessagesMsgTypeEnum.MsgType11.getCode());
            //List<ExtWFlowFormBackBid> wFlowFormBackBids = wFlowFormBackBidService.getExtBackBidByFormId(formId);

            List<ExtWFlowFormBidNoticeThanks> wFlowFormBidNoticeThanks = wFlowFormBidNoticeThanksService.getExtByFormIdAndType(formId, null);

            //设置发送时间
            wFlowFormBidNoticeThanksService.setSendTimeByFormId(formId);
            for (ExtWFlowFormBidNoticeThanks wFlowFormBidNoticeThank : wFlowFormBidNoticeThanks) {
                SMessages sMessages = new SMessages();
                sMessages.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                sMessages.setBidSupplierId(wFlowFormBidNoticeThank.getSupplierId());
                sMessages.setUserIds(wFlowFormBidNoticeThank.getSupplierId());
                sMessages.setFlowFormId(formId);
                sMessages.setReadFlag(CommonConstants.NO_INTEGER);
                sMessages.setSubRelatedId(wFlowFormBidNoticeThank.getId());
                if (wFlowFormBidNoticeThank.getNoticeType() == PurchaseCommonEnum.NOTICE_TYPE.getCode()) {
                    sMessages.setMsgContent(MessageFormat.format(sMessageTemplate.getMsgContent(), wFlowForm.getPurchaseItemName(), "标段" + wFlowFormBidNoticeThank.getSegmentsNumber()));
                    sMessages.setMsgTitle(MessageFormat.format(sMessageTemplate.getMsgName(), wFlowForm.getPurchaseItemName(), "标段" + wFlowFormBidNoticeThank.getSegmentsNumber()));
                    sMessages.setMsgType(MessagesMsgTypeEnum.MsgType12.getCode());
                    sMessages.setBidCategoryId(wFlowForm.getPurchaseClassification());
                } else {
                    sMessages.setMsgContent(MessageFormat.format(sMessageTemplate1.getMsgContent(), wFlowForm.getPurchaseItemName(), "标段" + wFlowFormBidNoticeThank.getSegmentsNumber()));
                    sMessages.setMsgTitle(MessageFormat.format(sMessageTemplate1.getMsgName(), wFlowForm.getPurchaseItemName(), "标段" + wFlowFormBidNoticeThank.getSegmentsNumber()));
                    sMessages.setMsgType(MessagesMsgTypeEnum.MsgType11.getCode());
                }
                sMessagesService.insert(sMessages);
            }
            LicenseUtil.INSTANCE.validate();
            updatecalibrationStatus(formId, PurchaseNodeButtonStatusEnum.PURCHASE_NODE_12_STATUS_5.getCode());
            wFlowFormBidNoticeThanksService.setSendTimeByFormId(formId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }


    public void updatecalibrationStatus(String formId, Integer status) {
        WFlowSubForm wFlowSubForm = new WFlowSubForm();
        wFlowSubForm.setFlowFormId(formId);
        wFlowSubForm.setCalibrationBidStatus(status);
        wFlowSubForm.setCalibrationBidTime(DateUtils.getNow());
        wFlowSubFormService.updateByFormId(wFlowSubForm);
    }


    public void saveWorkOrderCommonMethod(WFlowForm wForm, String handleUser, ProcessInstance processInstance, Map<String, Object> map) {
        Map<String, Object> mapResult = activitiTaskService.getTaskIdAndNamesProcessInstanceId(processInstance.getId());
        String taskIds = StringUtils.object2StringNotNull(mapResult.get("TASK_IDS"));
        String taskNames = StringUtils.object2StringNotNull(mapResult.get("TASK_NAMES"));
        wForm.setProcInstanceId(processInstance.getId());
        wForm.setProcDefinitionId(processInstance.getProcessDefinitionId());
        wForm.setTaskIds(taskIds);
        wForm.setTaskNames(taskNames);
        wFlowFormService.insert(wForm);
        ////生成流程流转后的待办
        generateFlowGoneMyDeals(wForm, handleUser, "", "", taskIds, taskNames, null);
        //更新flowFormStatus

    }

    public void updateWFlowFormStatus(String flowFormId) {
        Map<String, Object> param = Maps.newHashMapWithExpectedSize(1);
        param.put("flowFormId", flowFormId);
        List<WFlowFormSteps> list = wFlowFormStepsService.getWFlowFormStepsByCnd(param);
        StringBuilder lineStatus = new StringBuilder();
        for (WFlowFormSteps w : list) {
            lineStatus.append(w.getLineStatus()).append(",");
        }
        //SysDict sd = sysDictService.getSysDictByLabelAndType(lineStatus + "", CommonConstants.SYS_DICT_TYPE_PURCHASE_STATUS_MAP);//sysDictService.selectOne(new EntityWrapper<SysDict>().eq("dict_label", lineStatus).
        //eq("dict_type",CommonConstants.SYS_DICT_TYPE_PURCHASE_STATUS_MAP));
        WFlowForm wFlowForm = new WFlowForm();
        wFlowForm.setId(flowFormId);
        LicenseUtil.INSTANCE.validate();
        String flowFormLineStatus = lineStatus.toString();
        flowFormLineStatus = flowFormLineStatus.substring(0, flowFormLineStatus.length() - 1);
        wFlowForm.setFlowFormStatus(flowFormLineStatus);
        wFlowFormService.updateById(wFlowForm);
    }

    /***
     * 生成流程流转后的待办
     * @param wFlowForm
     * @param currentTaskId
     * @param oldTaskIds
     * @param newTaskIds
     */
    private void generateFlowGoneMyDeals(WFlowForm wFlowForm, String handleUser, String currentTaskId,
                                         String oldTaskIds, String newTaskIds, String newtaskNames, FlowTurnVO flowTurnVO) {
//		String taskIds = StringUtils.getListRemoves(oldTaskIds, currentTaskId);
//		taskIds = StringUtils.getListRemoves(newTaskIds, taskIds);
        ////设置当前task的步骤为已处理
        Map<String, Object> mapParams = new HashMap<String, Object>();
        if (StringUtils.isNotEmpty(currentTaskId)) {
            mapParams.put("flowFormId", wFlowForm.getId());
            mapParams.put("doneFlag", CommonConstants.NO_INTEGER);
            mapParams.put("lstTaskIds", Arrays.asList(new String[]{currentTaskId}));
//			mapParams.put("taskId", currentTaskId);
//			mapParams.put("doneFlag", CommonConstants.YES_INTEGER);
//			mapParams.put("updateDate", DateUtils.getNow());
//			wFlowFormStepsService.updateWFlowFormStepsByMap(mapParams);

            List<WFlowFormSteps> lstCurrentSteps = wFlowFormStepsService.getWFlowFormStepsByCnd(mapParams);
            if (CollectionUtils.isNotEmpty(lstCurrentSteps)) {
                WFlowFormSteps updatWFlowFormSteps = new WFlowFormSteps();
                updatWFlowFormSteps.setId(lstCurrentSteps.get(0).getId());
                updatWFlowFormSteps.setDoneFlag(CommonConstants.YES_INTEGER);
                updatWFlowFormSteps.setUpdateDate(DateUtils.getNow());
                wFlowFormStepsService.updateById(updatWFlowFormSteps);
            }
        }

        String updateTaskId = newTaskIds;
        String updateTaskName = newtaskNames;
        ////生成对应的待办
        //System.out.println(Thread.currentThread().getId()+"--"+Thread.currentThread().getName());


        LicenseUtil.INSTANCE.validate();
        ThreadLocalWFlowFormSteps threadLocalWFlowFormSteps = ThreadLocalWFlowFormSteps.getInstance();
        List<WFlowFormSteps> lstWFlowFormSteps = threadLocalWFlowFormSteps.getItem();
        if (!CollectionUtils.isEmpty(lstWFlowFormSteps)) {
            for (WFlowFormSteps wFlowFormSteps : lstWFlowFormSteps) {
                //lineStatus.append(wFlowFormSteps.getLineStatus()).append(",");
                ///根据流程执行实例id，更新步骤中的流程任务实例id
                String taskId = "";
                ;//activitiTaskService.getTaskIdsByExecutionId(wFlowFormSteps.getExecutionId());
                if (StringUtils.isNotEmpty(wFlowFormSteps.getProcessNodeLineConfigId())) {
                    AProcessNodeLineConfig aProcessNodeLineConfig = aProcessNodeLineConfigService.selectById(wFlowFormSteps.getProcessNodeLineConfigId());
                    if (aProcessNodeLineConfig != null && StringUtils.isNotEmpty((aProcessNodeLineConfig.getToNodeConfigId()))) {
                        AProcessNodeConfig aProcessNodeConfig = aProcessNodeConfigService.selectById(aProcessNodeLineConfig.getToNodeConfigId());
                        if (aProcessNodeConfig != null && StringUtils.isNotEmpty(aProcessNodeConfig.getNodeKey())) {
                            List<Task> lstTask = activitiTaskService.getTasksByProcessInstanceId(wFlowForm.getProcInstanceId(), aProcessNodeConfig.getNodeKey());
                            if (CollectionUtils.isNotEmpty(lstTask)) {
                                Task task = lstTask.get(0);
                                taskId = task.getId();
                                wFlowFormSteps.setExecutionId(task.getExecutionId());
                            }
                        }
                    }
                }
                updateWFlowFormStepsTaskId(wFlowFormSteps, taskId);
                //获取之前一个节点
                WFlowFormSteps preWFlowFormSteps = wFlowFormStepsService.getWFlowFormStepsByFormAndTaskId(wFlowForm.getId(), currentTaskId);
                if (preWFlowFormSteps == null) {
                    preWFlowFormSteps = new WFlowFormSteps();
                    preWFlowFormSteps.setLineStatus(-1);
                }
                List<String> newTaskIdList = StringUtils.getListBySplitStr(newTaskIds);
                if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode()) {//如果当前节点是流标
                    if (newTaskIdList.size() > 1) {
                        for (String id : newTaskIdList) {
                            if (!taskId.equals(id)) {
                                sMyDealsService.updateDeleteStatusByRelateIdAndTaskId(wFlowForm.getId(), id, CommonConstants.DEL_FLAG_DELETE);
                            }
                        }
                    }
                    updateTaskId = taskId;
                    updateTaskName = "流标中";
                    if (wFlowForm.getAbortiveFlag() != CommonConstants.ABORTIVE_BID_NOT) {
                        throw new RuntimeException("当前流标中", new ServiceThrowable());
                    }
                } else if (preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode()) {
                    if (newTaskIdList.size() > 1) {
                        for (String id : newTaskIdList) {
                            if (!taskId.equals(id)) {
                                sMyDealsService.updateDeleteStatusByRelateIdAndTaskId(wFlowForm.getId(), id, CommonConstants.DEL_FLAG_NORMAL);
                            }
                        }
                    }
                }

                //保存流程流转的额外数据
                saveFlowFormExtraData(wFlowFormSteps, preWFlowFormSteps, wFlowForm, handleUser, flowTurnVO);

                //保存下一个节点的初始数据

                saveNextFlowNodeData(wFlowFormSteps, preWFlowFormSteps, wFlowForm, flowTurnVO);


            }
        } else {
            //跟新taskId 和name 行状态
            if (StringUtils.isEmpty(updateTaskId)) {
                if (wFlowForm.getTaskNames().contains("定标"))
                    updateTaskName = "已定标";
                else {
                    updateTaskName = "已流标";
                }
            }
        }
        StringBuilder lineStatus = new StringBuilder();
        Map<String, Object> param = Maps.newHashMapWithExpectedSize(2);
        param.put("flowFormId", wFlowForm.getId());
        param.put("doneFlag", CommonConstants.UNDONG_FLAG);
        List<WFlowFormSteps> ll = wFlowFormStepsService.getWFlowFormStepsByCnd(param);
        if (CollectionUtils.isNotEmpty(ll)) {
            lineStatus.delete(0, lineStatus.length());
            for (WFlowFormSteps w : ll) {
                lineStatus.append(w.getLineStatus()).append(",");
                //updateTaskName +=","+sysDictService.getSysDictByLabelAndType(w.getLineStatus()+"","purchase_status_map").getDictDescription();
            }
        }


        String flowFormSubLineStatus = lineStatus.toString();
        if (!StringUtils.isEmpty(flowFormSubLineStatus))
            flowFormSubLineStatus = flowFormSubLineStatus.substring(0, flowFormSubLineStatus.length() - 1);

        String[] strings = flowFormSubLineStatus.split(",");
        Arrays.sort(strings);
        flowFormSubLineStatus = StringUtils.arr2String(strings);

        if (flowFormSubLineStatus.contains(WorkFlowLineStatusEnum.LINE_STATUS_END_GONE_BID.getCode() + "")) {
            flowFormSubLineStatus = WorkFlowLineStatusEnum.LINE_STATUS_END_GONE_BID.getCode() + "";
        } else if (flowFormSubLineStatus.contains(WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode() + "")) {
            flowFormSubLineStatus = WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode() + "";
        } else if (flowFormSubLineStatus.contains(WorkFlowLineStatusEnum.LINE_STATUS_END_CALIBRATION_BID.getCode() + "")) {
            flowFormSubLineStatus = WorkFlowLineStatusEnum.LINE_STATUS_END_CALIBRATION_BID.getCode() + "";
        }

        String flowFormStatus = sysDictService.getSysDictByLabelAndType(flowFormSubLineStatus.split(",")[0],
                CommonConstants.SYS_DICT_TYPE_PURCHASE_STATUS_MAP).getDictValue();
        WFlowForm wFlowForm1 = new WFlowForm();
        wFlowForm1.setId(wFlowForm.getId());
        wFlowForm1.setTaskIds(updateTaskId);
        wFlowForm1.setTaskNames(updateTaskName);
        if (!flowFormSubLineStatus.equals(WorkFlowLineStatusEnum.LINE_STATUS_END_GONE_BID.getCode() + "") &&
                !flowFormSubLineStatus.equals(WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode() + "") &&
                !flowFormSubLineStatus.contains(WorkFlowLineStatusEnum.LINE_STATUS_END_CALIBRATION_BID.getCode() + ""))
            wFlowForm1.setFlowFormSubStatus(flowFormSubLineStatus);
        wFlowForm1.setFlowFormStatus(flowFormStatus);
        wFlowFormService.updateById(wFlowForm1);
    }

    /***
     * 根据流程执行实例id，更新步骤中的流程任务实例id
     * @param wFlowFormSteps
     */
    private void updateWFlowFormStepsTaskId(WFlowFormSteps wFlowFormSteps, String taskId) {
        WFlowFormSteps item = new WFlowFormSteps();
        item.setId(wFlowFormSteps.getId());
        if (StringUtils.isNotEmpty(taskId)) {
            item.setTaskId(taskId);
            wFlowFormSteps.setTaskId(item.getTaskId());
            wFlowFormStepsService.updateById(item);
        }
    }

    /**
     * 流程-流转
     *
     * @param processConfigId
     * @param currentTaskId
     * @param currentUserId
     * @param goFlag
     */
    public void transferFlowProcess(String processConfigId, String currentTaskId, String currentUserId, int goFlag) {
        /// 流程流转
        Map<String, Object> variables = null;
        if (goFlag != WorkFlowGoneEnum.GO_FLAG_NONE.getCode()) {
            variables = new HashMap<String, Object>();
            variables.put("pass", goFlag + "");
        }

        LicenseUtil.INSTANCE.validate();
        boolean isCountSign = aProcessNodeConfigService.isCountSign(processConfigId, currentTaskId);
        if (isCountSign) {
            activitiTaskService.completeTask(currentTaskId, variables);
        } else {
            activitiTaskService.completeCandidateTask(currentTaskId, currentUserId, variables);
        }
    }

    /***
     * 保存流程流转的额外数据
     * @param wFlowFormSteps
     * @param wFlowForm
     * @param flowTurnVO
     */
    public void saveFlowFormExtraData(WFlowFormSteps wFlowFormSteps, WFlowFormSteps preWFlowFormSteps, WFlowForm wFlowForm, String handleUser, FlowTurnVO flowTurnVO) {
        if (wFlowFormSteps.getLineStatus() != null) {
            updateWfformMbsStatus(wFlowForm.getId(), WFlowFormStatusEnum.MBS_BPM_FLAG_1.getCode());//流转重置mbs审批状态
            preNodeIsAbortiveHandel(wFlowForm, wFlowFormSteps, preWFlowFormSteps, flowTurnVO);
            SysDict sysDict = sysDictService.getSysDictByLabelAndType(wFlowFormSteps.getLineStatus() + "", CommonConstants.SYS_DICT_TYPE_PURCHASE_STATUS_MAP);
            if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_PURCHASE_SCHEME.getCode()) {//采购方案
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_PURCHASE_PLAN_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.PURCHASE_PLAN.getCode(),
                        MyDealActionTypeEnum.PURCHASE_PLAN.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));
                sHistoryCommentService.insert(buildCommonHistory(wFlowForm.getId(), wFlowForm.getId(),
                        HistoryCommentModelTypeEnum.HistoryCommentModelType12.getCode(), "", PurchaseActionNameEnum.PURCHASE_PLAN_1_4.getDesc(),
                        PurchaseNodeEnum.NODE_1_4.getDesc(), 0, false));
            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_SUPPLIER_ENTRY.getCode()) {//供应商入围
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_SUPPLIER_ENTRY_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.SUPPLIER_ENTRY.getCode(),
                        MyDealActionTypeEnum.SUPPLIER_ENTRY.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));
            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_BID_DOC.getCode()) {//招标文件
                if (preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode()) {
                    SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_LINE_STATUS_BID_DOC_DEAL.getCode());
                    sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                            MyDealSubTypeEnum.BIDDING_DOCUMENTS.getCode(),
                            MyDealActionTypeEnum.BIDDING_DOCUMENTS.getCode(),
                            MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                            handleUser, null, wFlowFormSteps.getTaskId()));
                }
            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_SEND_BID.getCode()) {//发标
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_SEND_BID_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.SEND_BID.getCode(),
                        MyDealActionTypeEnum.SEND_BID.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));
            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_ANSWER_ADDENDUM.getCode()) {//答疑补遗
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_QUESTION_ASK_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.QUE_ANSWER.getCode(),
                        MyDealActionTypeEnum.QUE_ANSWER.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));
            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_BACK_BID.getCode()) {//回标
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_QUESTION_ASK_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.RETURN_BID.getCode(),
                        MyDealActionTypeEnum.RETURN_BID.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));

            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_TWO_BACK_BID.getCode()) {//二轮回标
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_TWO_BACK_BID_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.TWO_RETURN_BID.getCode(),
                        MyDealActionTypeEnum.TWO_RETURN_BID.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));
            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_OPEN_BID.getCode()) {//开标
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_OPEN_BID_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.OPEN_BID.getCode(),
                        MyDealActionTypeEnum.OPEN_BID.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));
            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_TENDER_BID.getCode()) {//询标
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_INQUIRING_BID_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.INQUIRING_BID.getCode(),
                        MyDealActionTypeEnum.INQUIRING_BID.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));
            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_BUSINESS_NEGOTIATION.getCode()) {//商务谈判
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_BUSINESS_NEGOTIATION_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.BUSINESS_NEGOTIATION.getCode(),
                        MyDealActionTypeEnum.BUSINESS_NEGOTIATION.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));
            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_EVALUATE_BID.getCode()) {//评标
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_PING_BID_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.PING_BID.getCode(),
                        MyDealActionTypeEnum.PING_BID.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));

            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_CALIBRATION_BID.getCode()) {//定标
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_DING_BID_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.CALIBRATION.getCode(),
                        MyDealActionTypeEnum.CALIBRATION.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));
            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode()) {//流标
                SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.P_NODE_ABORTIVE_BID_DEAL.getCode());
                sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                        MyDealSubTypeEnum.ABORTIVE_LOOK_THROUGH.getCode(),
                        MyDealActionTypeEnum.ABORTIVE_LOOK_THROUGH.getCode(),
                        MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName(), sysDict.getDictDescription()),
                        handleUser, null, wFlowFormSteps.getTaskId()));

                String nodeNameHistory = sCommentConfigService.getValueByCode(CommentConfigEnum.P_NODE_ABORTIVE_BID_HISTORY.getCode());
                sysDict = sysDictService.getSysDictByLabelAndType(wFlowForm.getAbortiveType() + "", CommonConstants.SYS_DICT_TYPE_PURCHASE_STATUS_MAP);
                nodeNameHistory = MessageFormat.format(nodeNameHistory, sysDict.getDictDescription());
                sHistoryCommentService.insert(buildCommonHistory(wFlowForm.getId(), wFlowForm.getId(),
                        HistoryCommentModelTypeEnum.HistoryCommentModelType13.getCode(), flowTurnVO.getReason(), PurchaseActionNameEnum.PURCHASE_PLAN_6_1.getDesc(),
                        nodeNameHistory, 0, false));
            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_END_CALIBRATION_BID.getCode()) {//定标结束

            } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_END_GONE_BID.getCode()) {//流标结束
                String nodeNameHistory = sCommentConfigService.getValueByCode(CommentConfigEnum.P_NODE_ABORTIVE_BID_HISTORY.getCode());
                sysDict = sysDictService.getSysDictByLabelAndType(wFlowForm.getAbortiveType() + "", CommonConstants.SYS_DICT_TYPE_PURCHASE_STATUS_MAP);
                nodeNameHistory = MessageFormat.format(nodeNameHistory, sysDict.getDictDescription());

                sHistoryCommentService.insert(buildCommonHistory(wFlowForm.getId(), wFlowForm.getId(), HistoryCommentModelTypeEnum.
                                HistoryCommentModelType13.getCode(), flowTurnVO.getReason(), PurchaseActionNameEnum.PURCHASE_PLAN_6_2.getDesc(),
                        nodeNameHistory, CommonConstants.AGREE_FLAG, false));
            }
        }
    }

    /**
     * 判断上一个节点是不是流标
     */
    public void preNodeIsAbortiveHandel(WFlowForm wFlowForm, WFlowFormSteps wFlowFormSteps, WFlowFormSteps preWFlowFormSteps, FlowTurnVO flowTurnVO) {
        if (preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode()
                && wFlowFormSteps.getLineStatus() != WorkFlowLineStatusEnum.LINE_STATUS_END_GONE_BID.getCode()) {

            String nodeNameHistory = sCommentConfigService.getValueByCode(CommentConfigEnum.P_NODE_ABORTIVE_BID_HISTORY.getCode());
            SysDict sysDict = sysDictService.getSysDictByLabelAndType(wFlowForm.getAbortiveType() + "", CommonConstants.SYS_DICT_TYPE_PURCHASE_STATUS_MAP);

            nodeNameHistory = MessageFormat.format(nodeNameHistory, sysDict.getDictDescription());
            sHistoryCommentService.insert(buildCommonHistory(wFlowForm.getId(), wFlowForm.getId(), HistoryCommentModelTypeEnum.
                            HistoryCommentModelType13.getCode(), flowTurnVO.getReason(), PurchaseActionNameEnum.PURCHASE_PLAN_6_3.getDesc(),
                    nodeNameHistory, CommonConstants.NO_AGREE_FLAG, false));

        }
        LicenseUtil.INSTANCE.validate();
    }

    void updateFlowBidAuditedTime(WFlowForm wFlowForm) {
        WFlowForm wFlowForm1 = new WFlowForm();
        wFlowForm1.setId(wFlowForm.getId());
        wFlowForm1.setAbortiveAuditedTime(DateUtils.getNow());
        wFlowFormService.updateById(wFlowForm1);
    }

    /***
     * 保存下一个节点的初始数据
     * @param wFlowFormSteps
     */
    public void saveNextFlowNodeData(WFlowFormSteps wFlowFormSteps, WFlowFormSteps preWFlowFormSteps, WFlowForm wFlowForm, FlowTurnVO flowTurnVO) {
        if (wFlowFormSteps.getLineStatus() != null) {
            //节点流转后预制数据
            if (wFlowFormSteps.getLineStatus() != WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode()) {
                if (preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_SUPPLIER_ENTRY.getCode() ||
                        preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_BID_DOC.getCode()) {
                    saveSupplierEntryNextNodeData(wFlowForm);
                } else if (preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_PURCHASE_SCHEME.getCode()) {
                    if (wFlowFormSteps.getLineStatus() != WorkFlowLineStatusEnum.LINE_STATUS_SUPPLIER_ENTRY.getCode() &&
                            wFlowFormSteps.getLineStatus() != WorkFlowLineStatusEnum.LINE_STATUS_BID_DOC.getCode())
                        savePPlanNextNodeData(wFlowForm);
                } else if (preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_TENDER_BID.getCode()) {
                    //更新询标技术评分
                    updateTechnologyScore(wFlowForm);
                } else if (preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_SEND_BID.getCode()) {
                    preSendBidHandle(wFlowForm, flowTurnVO);
                } else if (preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_BACK_BID.getCode()) {
                    //更新没有回标的供应商标段 终止
                    //updateBackBidInvalid(wFlowForm,1);
                    updateBackBidOuterStatus(wFlowForm.getId(), 1);
                    doneMydeal(wFlowForm.getId(), MyDealActionTypeEnum.RETURN_BID.getCode());
                } else if (preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_TWO_BACK_BID.getCode()) {
                    updateBackBidOuterStatus(wFlowForm.getId(), 2);
                    doneMydeal(wFlowForm.getId(), MyDealActionTypeEnum.TWO_RETURN_BID.getCode());
                } else if (preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_BUSINESS_NEGOTIATION.getCode()) {
                    if (isNeedOuterInteract(wFlowForm)) {
                        updateBackBidOuterStatus(wFlowForm.getId(), 3);
                        doneMydeal(wFlowForm.getId(), MyDealActionTypeEnum.BUSINESS_NEGOTIATION.getCode());
                    }
                } else if (preWFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_EVALUATE_BID.getCode()) {
                    updateBackBidOuterStatus(wFlowForm.getId(), 4);
                    doneMydeal(wFlowForm.getId(), MyDealActionTypeEnum.PING_BID_INTERVIEW_OUT.getCode());
                    //插入评标结论
                    if (StringUtils.isNotEmpty(flowTurnVO.getBidEvaluationConclusion())) {
                        WFlowForm wFlowForm1 = new WFlowForm();
                        wFlowForm1.setId(wFlowForm.getId());
                        wFlowForm1.setBidEvaluationConclusion(flowTurnVO.getBidEvaluationConclusion());
                        wFlowFormService.updateById(wFlowForm1);
                    }
                }
            }

            LicenseUtil.INSTANCE.validate();
            //当前节点需要的数据
            if (preWFlowFormSteps.getLineStatus() != WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode()) {
                if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_PURCHASE_SCHEME.getCode()) {//采购方案
                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_SUPPLIER_ENTRY.getCode()) {//供应商入围
                    saveInvitationNextnodeData(wFlowForm);
                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_BID_DOC.getCode()) {//招标文件
                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_SEND_BID.getCode()) {//发标
                    sendBiddingNodeData(wFlowForm);
                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_ANSWER_ADDENDUM.getCode()) {//答疑补遗
                    saveWflowFormQuestionAnswer(wFlowForm);
                    List<String> supplierIds = wFlowFormSupplierEntryService.getSupplierIdsWithAgree(wFlowForm.getId());
                    for (String supplierId : supplierIds) {
                        WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(wFlowForm.getId(), supplierId);
                        wFlowFormExtMng.setFlowFormSubStatus(WFlowFormExtSubEnum.STATUS_1_5.getCode() + "");
                        wFlowFormExtMngService.updateById(wFlowFormExtMng);

                    }
                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_BACK_BID.getCode()) {//回标
                    turnBidHandel(wFlowForm);
                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_TWO_BACK_BID.getCode()) {//二轮回标
                    //wFlowFormBackBidService.updateBackBidStatusByFormId(wFlowForm.getId(),CommonConstants.NO_INTEGER);
                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_OPEN_BID.getCode()) {//开标
                    generateDarkCode(wFlowForm);
                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_TENDER_BID.getCode()) {//询标
                    saveInquiringBidNodeData(wFlowForm);
                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_BUSINESS_NEGOTIATION.getCode()) {//商务谈判

                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_EVALUATE_BID.getCode()) {//评标

                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_CALIBRATION_BID.getCode()) {//定标
                    handelDingbid(wFlowForm);
                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_GONE_BID.getCode()) {//流标
                    abortiveDataHandle(wFlowForm, CommonConstants.ABORTIVE_BID_ING);
                } else if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_END_CALIBRATION_BID.getCode()) {//定标结束
                    //saveAndUpdateCalibratedBidData(wFlowForm.getId());
                    calibrationBidEnd(wFlowForm);
                }
            } else {//上个节点是流标
                if (wFlowFormSteps.getLineStatus() == WorkFlowLineStatusEnum.LINE_STATUS_END_GONE_BID.getCode()) {//流标结束
                    abortiveDataHandle(wFlowForm, CommonConstants.ABORTIVE_BID_OK);
                    //更新外网状态为流标
                    //wFlowFormExtMngService.updateStatusByFormIdAndStatusNEqStatus(WFlowFormExtEnum.STATUS_6.getCode()+"",wFlowForm.getId(),null);
                    //更新所有的代办为已处理
//					SMyDeals sMyDeals = new SMyDeals();
//					sMyDeals.setRelatedId(wFlowForm.getId());
//					sMyDeals.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
//					sMyDeals.setDoneFlag(CommonConstants.NO_INTEGER);
//					sMyDealsService.doneByEntityAndUsers(sMyDeals,null,"已流标");

                    //更新计划状态
                    if (wFlowForm.getPurchasePlanType() == PurchaseCommonEnum.PURCHASE_PLAN_TYPE_SPECIAL.getCode()) {
                        String planId = wFlowForm.getPurchasePlanId();
                        PSpecialPurchasePlan pSpecialPurchasePlan = new PSpecialPurchasePlan();
                        pSpecialPurchasePlan.setId(planId);
                        pSpecialPurchasePlan.setPlanStatus(PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_3.getCode());
                        pSpecialPurchasePlanService.updatePSpecialPurchasePlan(pSpecialPurchasePlan);
                    } else {
                        //todo 战略
                        PStrategicPurchaseContact pStrategicPurchaseContact = new PStrategicPurchaseContact();
                        pStrategicPurchaseContact.setId(wFlowForm.getPurchasePlanId());
                        pStrategicPurchaseContact.setPurchaseItemStatus(PurchaseCommonEnum.P_OVER_PLAN_STATUS_3.getCode());
                        pStrategicPurchaseContactService.updateById(pStrategicPurchaseContact);
                    }
                    //设置所有的代办为已办
                    doneMydeal(wFlowForm.getId(), null);

                    //通知招标项状态
                    SynSourcingDataVo synSourcingDataVo = new SynSourcingDataVo();
                    synSourcingDataVo.setSrId(wFlowForm.getContractId());
                    synSourcingDataVo.setSrStatus("0");
                    synDataService.changeSourcingStatus(synSourcingDataVo);
                } else {
                    abortiveDataHandle(wFlowForm, CommonConstants.ABORTIVE_BID_NOT);
                }

            }
        }
    }

    /**
     * 上一个节点是发标的处理
     *
     * @param wFlowForm
     */
    void preSendBidHandle(WFlowForm wFlowForm, FlowTurnVO flowTurnVO) {
        sendBidDealToOuter(wFlowForm, flowTurnVO);
        WFlowSubForm wFlowSubForm = new WFlowSubForm();
        wFlowSubForm.setFlowFormId(wFlowForm.getId());
        wFlowSubForm.setSendBidStatus(CommonConstants.YES_INTEGER);
        wFlowSubForm.setSendBidTime(DateUtils.getNow());
        wFlowSubFormService.updateByFormId(wFlowSubForm);
    }

    void doneMydeal(String formId, Integer actionType) {
        SMyDeals sMyDeals = new SMyDeals();
        if (actionType != null)
            sMyDeals.setActionType(actionType);
        sMyDeals.setRelatedId(formId);
        sMyDealsService.doneByEntityAndUsers(sMyDeals, null, "过期失效");
    }

    /**
     * 流转到回标节点
     */
    public void turnBidHandel(WFlowForm wFlowForm) {
        //supplierIds.addAll(wFlowFormSupplierEntryService.getSupplierIdsWithAgree(wFlowForm.getId()));
        Map<String, Object> param = new HashMap<>(2);
        param.put("sendBidStatus", CommonConstants.YES_INTEGER);
        param.put("formId", wFlowForm.getId());
        List<String> supplierIds = wFlowFormBackBidService.selectSupplieridsByMap(param);
        WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(wFlowForm.getId());
        //sendBackBidDeal(wFlowForm.getId(),null,1,wFlowFormTimeNode.getBackBid());
        String snName = "(标段1";
        for (int i = 2; i <= wFlowForm.getSegmentsNumber(); i++) {
            snName += ",标段" + i;
        }
        LicenseUtil.INSTANCE.validate();
        snName += ")";
        for (String supplierId : supplierIds) {
            WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(wFlowForm.getId(), supplierId);
            List<WFlowFormExtSubMng> wFlowFormExtSubMngs = wFlowFormExtSubMngService.getByParentId(wFlowFormExtMng.getId());
            for (WFlowFormExtSubMng wFlowFormExtSubMng : wFlowFormExtSubMngs) {
                wFlowFormExtSubMng.setActionStatus(WFlowFormExtSubEnum.STATUS_4_2.getCode());
                wFlowFormExtSubMngService.updateById(wFlowFormExtSubMng);
            }
            sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                    MyDealSubTypeEnum.BACK_BID_OUT.getCode(),
                    MyDealActionTypeEnum.RETURN_BID_OUT.getCode(),
                    MessageFormat.format(
                            sCommentConfigService.getValueByCode(CommentConfigEnum.PURCHASE_OUTER_BACK_BID_DEAL.getCode()),
                            wFlowForm.getPurchaseItemName(), snName
                    ),
                    supplierId, wFlowFormTimeNode.getBackBid(), null));
        }
    }

    /**
     *
     */
    void handelDingbid(WFlowForm wFlowForm) {
        if (wFlowForm.getFlowType() == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_6.getCode()) {
            wFlowFormBackBidService.updateAwardBidByFormId(wFlowForm.getId());
        }
    }

    /**
     * 判断是否是有外网交互的外网类型
     *
     * @param wFlowForm
     */
    public boolean isNeedOuterInteract(WFlowForm wFlowForm) {
        Integer flowType = wFlowForm.getFlowType();
        if (flowType == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_4.getCode() ||
                flowType == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_5.getCode() ||
                flowType == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_6.getCode())
            return false;
        else return true;

    }

    public void calibrationBidEnd(WFlowForm wFlowForm) {
        Date now = DateUtils.getNow();
        String formId = wFlowForm.getId();
        List<ExtWFlowFormBackBid> wFlowFormBackBids = wFlowFormBackBidService.getExtBackBidByFormId(formId);
        String ids = "";
        String title = "";
        Integer flowType = wFlowForm.getFlowType();
        SMessageTemplate sMessageTemplate = null;
        if (flowType == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_4.getCode() ||
                flowType == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_5.getCode() ||
                flowType == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_6.getCode()) {
            sMessageTemplate = sMessageTemplateService.getByMsgType(MessagesMsgTypeEnum.MsgType13.getCode());//中标通知
        }
        for (ExtWFlowFormBackBid wFlowFormBackBid : wFlowFormBackBids) {
            WFlowFormExtMng wFlowFormExtMng = null;
            WFlowFormExtSubMng wFlowFormExtSubMng = null;
            //外网进程历史
            SHistoryComment sHistoryComment = null;
            if (isNeedOuterInteract(wFlowForm)) {
                wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(formId, wFlowFormBackBid.getSupplierId());
                wFlowFormExtSubMng = wFlowFormExtSubMngService.selectByParentIdAndSn(wFlowFormExtMng.getId(), wFlowFormBackBid.getSegmentsNumber());
            }


            if (wFlowFormBackBid.getAwardBidOrNot() == CommonConstants.YES_INTEGER) {
                if (isNeedOuterInteract(wFlowForm)) {
                    sHistoryComment = buildCommonHistory(formId, wFlowFormExtSubMng.getId(),
                            HistoryCommentModelTypeEnum.HistoryCommentModelType24.getCode(), "",
                            PurchaseActionNameEnum.PURCHASE_PLAN_9_1.getDesc(), PurchaseNodeEnum.NODE_10_1.getDesc(),
                            0, false);
                    sHistoryComment.setActionStatus(PurchaseCommonEnum.OUTER_PROCESS_STATUS_1.getCode());
                }

                if (flowType == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_4.getCode() ||
                        flowType == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_5.getCode() ||
                        flowType == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_6.getCode()) {//无中标通知书的招标类型发送中标消息
                    SMessages sMessages = new SMessages();
                    sMessages.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                    sMessages.setBidSupplierId(wFlowFormBackBid.getSupplierId());
                    sMessages.setUserIds(wFlowFormBackBid.getSupplierId());
                    sMessages.setFlowFormId(formId);
                    sMessages.setReadFlag(CommonConstants.NO_INTEGER);
                    sMessages.setMsgContent(MessageFormat.format(sMessageTemplate.getMsgContent(), wFlowForm.getPurchaseItemName(), "标段" + wFlowFormBackBid.getSegmentsNumber()));
                    sMessages.setMsgTitle(MessageFormat.format(sMessageTemplate.getMsgName(), wFlowForm.getPurchaseItemName(), "标段" + wFlowFormBackBid.getSegmentsNumber()));
                    sMessages.setMsgType(MessagesMsgTypeEnum.MsgType13.getCode());
                    sMessages.setBidCategoryId(wFlowForm.getPurchaseClassification());
                    sMessagesService.insert(sMessages);
                }

                ids += "," + wFlowFormBackBid.getSupplierId();
                if (wFlowForm.getSegmentsNumber() != 1) {
                    title += ";标段" + wFlowFormBackBid.getSegmentsNumber() + ":" + wFlowFormBackBid.getSupplierName();
                } else {
                    title = wFlowFormBackBid.getSupplierName();
                }


                //插入定标数据
                WFlowFormAwardBid wFlowFormAwardBid = new WFlowFormAwardBid();
                wFlowFormAwardBid.setAwardTime(now);
                wFlowFormAwardBid.setBaseFeilds(UserUtils.getCurrentUserId(), "",
                        CommonConstants.DEL_FLAG_NORMAL, true);
                wFlowFormAwardBid.setSupplierId(wFlowFormBackBid.getSupplierId());
                wFlowFormAwardBid.setDarkBidCode(wFlowFormBackBid.getDarkBidCode());
                wFlowFormAwardBid.setSegmentsNumber(wFlowFormBackBid.getSegmentsNumber());
                wFlowFormAwardBid.setFlowFormId(formId);
                Double finalInterviewInputTax = wFlowFormBackBid.getCalibrationFinalInputTax();
                Double finalInterviewWithTax = wFlowFormBackBid.getCalibrationFinalTax();
                if (finalInterviewInputTax == null) {
                    finalInterviewInputTax = wFlowFormBackBid.getFinalInterviewInputTax();
                    finalInterviewWithTax = wFlowFormBackBid.getFinalInterviewWithTax();
                }
                if (finalInterviewInputTax == null) {
                    finalInterviewInputTax = wFlowFormBackBid.getBusinessNegotiationInputTax();
                    finalInterviewWithTax = wFlowFormBackBid.getBusinessNegotiationWithTax();
                }
                if (finalInterviewInputTax == null) {
                    finalInterviewInputTax = wFlowFormBackBid.getRoundTwoInputTax();
                    finalInterviewWithTax = wFlowFormBackBid.getRoundTwoWithTax();
                }
                if (finalInterviewInputTax == null) {
                    finalInterviewInputTax = wFlowFormBackBid.getRoundOneInputTax();
                    finalInterviewWithTax = wFlowFormBackBid.getRoundOneWithTax();
                }

                wFlowFormAwardBid.setFinalInterviewInputTax(finalInterviewInputTax);
                wFlowFormAwardBid.setFinalInterviewWithTax(finalInterviewWithTax);
                wFlowFormAwardBidService.insert(wFlowFormAwardBid);
            } else {
                if (isNeedOuterInteract(wFlowForm)) {
                    sHistoryComment = buildCommonHistory(formId, wFlowFormExtSubMng.getId(),
                            HistoryCommentModelTypeEnum.HistoryCommentModelType24.getCode(), "",
                            PurchaseActionNameEnum.PURCHASE_PLAN_9_2.getDesc(), PurchaseNodeEnum.NODE_10_1.getDesc(),
                            0, false);
                    sHistoryComment.setActionStatus(PurchaseCommonEnum.OUTER_PROCESS_STATUS_2.getCode());
                }
            }
            if (isNeedOuterInteract(wFlowForm)) {
                sHistoryCommentService.insert(sHistoryComment);
            }
        }

        //生成中标公告
        ids = ids.substring(1);
        if (wFlowForm.getSegmentsNumber() != 1) {
            title = title.substring(1);
        }
        sMessageTemplate = sMessageTemplateService.getByMsgType(MessagesMsgTypeEnum.MsgType7.getCode());
        SMessages sMessages = new SMessages();
        sMessages.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
        sMessages.setBidSupplierId(ids);
        sMessages.setUserIds(ids);
        sMessages.setFlowFormId(formId);
        sMessages.setReadFlag(CommonConstants.NO_INTEGER);
        sMessages.setMsgContent(MessageFormat.format(sMessageTemplate.getMsgContent(), wFlowForm.getPurchaseItemName(), title));
        sMessages.setMsgTitle(MessageFormat.format(sMessageTemplate.getMsgName(), wFlowForm.getPurchaseItemName(), title));
        sMessages.setMsgType(MessagesMsgTypeEnum.MsgType7.getCode());
        sMessages.setBidCategoryId(wFlowForm.getPurchaseClassification());
        sMessagesService.insert(sMessages);


        WFlowForm w = new WFlowForm();
        w.setId(formId);
        w.setCalibrationFlag(PurchaseCommonEnum.CALIBRATION_FLAG_YES.getCode());
        w.setCalibrationTime(DateUtils.getNow());
        wFlowFormService.updateById(w);
        //更新外网状态
        if (isNeedOuterInteract(wFlowForm)) {
            EntityWrapper<WFlowFormExtMng> entityWrapper = new EntityWrapper();
            WFlowFormExtMng where = new WFlowFormExtMng();
            where.setFlowFormId(formId);
            entityWrapper.setEntity(where);
            entityWrapper.ne("flow_form_sub_status", WFlowFormExtSubEnum.STATUS_1_3.getCode() + "")
                    .and().ne("flow_form_status", WFlowFormExtEnum.STATUS_1.getCode() + "");
            WFlowFormExtMng wFlowFormExtMng = new WFlowFormExtMng();
            wFlowFormExtMng.setFlowFormStatus(WFlowFormExtEnum.STATUS_5.getCode() + "");
            wFlowFormExtMngService.update(wFlowFormExtMng, entityWrapper);
        }

        //设置所有的代办为已办
        doneMydeal(wFlowForm.getId(), null);

        if (wFlowForm.getPurchasePlanType() == PurchaseCommonEnum.PURCHASE_PLAN_TYPE_SPECIAL.getCode()) {
            String planId = wFlowForm.getPurchasePlanId();
            PSpecialPurchasePlan pSpecialPurchasePlan = new PSpecialPurchasePlan();
            pSpecialPurchasePlan.setId(planId);
            pSpecialPurchasePlan.setPlanStatus(PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_5.getCode());
            pSpecialPurchasePlanService.updatePSpecialPurchasePlan(pSpecialPurchasePlan);
        } else {
            PStrategicPurchaseContact pStrategicPurchaseContact = new PStrategicPurchaseContact();
            pStrategicPurchaseContact.setId(wFlowForm.getPurchasePlanId());
            pStrategicPurchaseContact.setPurchaseItemStatus(PurchaseCommonEnum.P_OVER_PLAN_STATUS_5.getCode());
            pStrategicPurchaseContactService.updateById(pStrategicPurchaseContact);
        }
    }

    /**
     * 更新回标外网状态
     *
     * @Param round(1 ： 回标后, 2 : 二轮回标, 3商务谈判 ， 4评标约谈)
     */
    public void updateBackBidOuterStatus(String formId, Integer round) {
        WFlowFormExtSubMng wFlowFormExtSubMng = new WFlowFormExtSubMng();
        wFlowFormExtSubMng.setFlowFormId(formId);
        Integer actionStatus = null;
        if (round == 1) {
            actionStatus = WFlowFormExtSubEnum.STATUS_4_3.getCode();
            wFlowFormExtSubMng.setActionStatus(WFlowFormExtSubEnum.STATUS_4_2.getCode());
        } else if (round == 2) {
            actionStatus = WFlowFormExtSubEnum.STATUS_4_7.getCode();
            wFlowFormExtSubMng.setActionStatus(WFlowFormExtSubEnum.STATUS_4_6.getCode());
        } else if (round == 3) {
            actionStatus = WFlowFormExtSubEnum.STATUS_4_9.getCode();
            wFlowFormExtSubMng.setActionStatus(WFlowFormExtSubEnum.STATUS_4_8.getCode());
        } else if (round == 4) {
            actionStatus = WFlowFormExtSubEnum.STATUS_4_11.getCode();
            wFlowFormExtSubMng.setActionStatus(WFlowFormExtSubEnum.STATUS_4_10.getCode());
        }
        wFlowFormExtSubMngService.updateByEntity(actionStatus, wFlowFormExtSubMng);
    }

    /**
     * 删除在规定节点内没有及时回标的代办
     *
     * @param wFlowForm
     * @param round     （1：回标 ，2二轮回标，3：商务谈判，4：评标约谈）
     */
    @Deprecated
    void deleteSMdealsOut(WFlowForm wFlowForm, int round) {
        SMyDeals sMyDeals = new SMyDeals();
        sMyDeals.setRelatedId(wFlowForm.getId());
        sMyDeals.setDealSubType(MyDealSubTypeEnum.BACK_BID_OUT.getCode());
        int actionType = 0;
        Map<String, Object> param = Maps.newHashMap();
        param.put("formId", wFlowForm.getId());
        if (round == 1) {
            actionType = MyDealActionTypeEnum.RETURN_BID_OUT.getCode();
            param.put("backBidOrNot", CommonConstants.NO_INTEGER);
        } else if (round == 2) {
            param.put("roundTwoBackBidOrNot", CommonConstants.NO_INTEGER);
            actionType = MyDealActionTypeEnum.RETURN_BID_TWO_OUT.getCode();
        } else if (round == 3) {
            actionType = MyDealActionTypeEnum.BUSINESS_NEGOTIATION_RETURN_BID_OUT.getCode();
        } else if (round == 4) {
            actionType = MyDealActionTypeEnum.PING_BID_INTERVIEW_OUT.getCode();
        }
        sMyDeals.setActionType(actionType);
        //sMyDealsService.deleteBatchByEntityAndUsers(sMyDeals,wFlowFormBackBidService.selectSupplierSysIdsByMap(param));
    }

    /**
     * 更新回标表 终止
     *
     * @param type (1:没有回标，2二轮发标后废标的 3，二轮没有回标的)
     */
    @Deprecated
    void updateBackBidInvalid(WFlowForm wFlowForm, Integer type) {
        WFlowFormBackBid wFlowFormBackBid = new WFlowFormBackBid();
        wFlowFormBackBid.setFlowFormId(wFlowForm.getId());
        wFlowFormBackBid.setDelFlag(CommonConstants.NO_INTEGER);
        if (type == 1) {//没有回标
            wFlowFormBackBid.setBackBidOrNot(CommonConstants.NO_INTEGER);
        } else if (type == 2) {//二轮发标后废标的
            wFlowFormBackBid.setAbandonedBidOrNot(CommonConstants.YES_INTEGER);
        }
        wFlowFormBackBidService.setInvild(wFlowFormBackBid);
    }

    /**
     * 发送回标代办到外网
     *
     * @param round (1:回标，2二轮回标，3 商务谈判，4评标约谈)
     */
    void sendBackBidDeal(String formId, List<WFlowFormBackBid> wFlowFormBackBids, Integer round, Date endTime) {
        Integer actionType = null;
        SCommentConfig sc = null;
        WFlowForm wFlowForm = wFlowFormService.selectById(formId);
        String title = "";
        if (round == 1) {//回标
//			actionType = MyDealActionTypeEnum.RETURN_BID_OUT.getCode();
//			sc = sCommentConfigService.getByCode(CommentConfigEnum.PURCHASE_OUTER_BACK_BID_DEAL.getCode());
        } else {
            if (round == 2) {//二轮回标
                actionType = MyDealActionTypeEnum.RETURN_BID_TWO_OUT.getCode();
                sc = sCommentConfigService.getByCode(CommentConfigEnum.PURCHASE_OUTER_TWO_BACK_BID_DEAL.getCode());
            } else if (round == 3) {//商务谈判
                actionType = MyDealActionTypeEnum.BUSINESS_NEGOTIATION_RETURN_BID_OUT.getCode();
                sc = sCommentConfigService.getByCode(CommentConfigEnum.PURCHASE_OUTER_BUSINESS_DEAL.getCode());
            } else {//评标约谈
                actionType = MyDealActionTypeEnum.PING_BID_INTERVIEW_OUT.getCode();
                sc = sCommentConfigService.getByCode(CommentConfigEnum.PURCHASE_OUTER_PING_BID_DEAL.getCode());
            }
        }
        title = sc.getConfigValue();
        if (wFlowFormBackBids != null) {
            Collections.sort(wFlowFormBackBids, (a, b) -> a.getSupplierId().compareTo(b.getSupplierId()));
            String suppliertem = "";
            String snTem = "";
            int n = 0;
            for (WFlowFormBackBid w : wFlowFormBackBids) {
                n++;
                if (suppliertem.equals(w.getSupplierId())) {
                    snTem += ",标段" + w.getSegmentsNumber();
                } else {
                    if (!suppliertem.equals(""))
                        sMyDealsService.insert(buildCommonDeals(formId, formId,
                                MyDealSubTypeEnum.BACK_BID_OUT.getCode(),
                                actionType,
                                MessageFormat.format(title, wFlowForm.getPurchaseItemName(), snTem + ")"),
                                suppliertem, endTime, null));

                    suppliertem = w.getSupplierId();
                    snTem = "(标段" + w.getSegmentsNumber();
                }

                if (n == wFlowFormBackBids.size()) {
                    sMyDealsService.insert(buildCommonDeals(formId, formId,
                            MyDealSubTypeEnum.BACK_BID_OUT.getCode(),
                            actionType,
                            MessageFormat.format(title, wFlowForm.getPurchaseItemName(), snTem + ")"),
                            suppliertem, endTime, null));
                }

            }
        }

    }

    /**
     * 发送标书下载代办
     */
    public void sendBidDealToOuter(WFlowForm wFlowForm, FlowTurnVO flowTurnVO) {
        List<String> suppliers = flowTurnVO.getSupplierIds();//wFlowFormSupplierEntryService.getSupplierIdsWithAgree(formId);
        String formId = wFlowForm.getId();
        SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.PURCHASE_BID_DOWN_DEAL.getCode());
        String title = MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName());

        WFlowFormBackBid where = new WFlowFormBackBid();
        where.setFlowFormId(wFlowForm.getId());
        WFlowFormBackBid wFlowFormBackBidUpdate = new WFlowFormBackBid();
        wFlowFormBackBidUpdate.setSendBidStatus(1);
        for (String s : suppliers) {
            where.setSupplierId(s);
            wFlowFormBackBidService.update(wFlowFormBackBidUpdate, new EntityWrapper<>(where));
            sMyDealsService.insert(buildCommonDeals(formId, formId,
                    MyDealSubTypeEnum.SEND_BID.getCode(),
                    MyDealActionTypeEnum.BIDS_DOWN_OUT.getCode(),
                    title,
                    s, null, null));

            updateSendBidOuterStatus(formId, s);
        }
    }


    public void sendBiddingNodeData(WFlowForm wFlowForm) {
        List<WFlowFormSupplierEntry> entries = wFlowFormSupplierEntryService.getReplyAgreeByFormId(wFlowForm.getId());
        for (WFlowFormSupplierEntry wFlowFormSupplierEntry : entries) {
            WFlowFormSendBid wFlowFormSendBid = new WFlowFormSendBid();
            wFlowFormSendBid.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.NO_INTEGER, true);
            wFlowFormSendBid.setDownloadOrNot(CommonConstants.NO_INTEGER);
            wFlowFormSendBid.setFlowFormId(wFlowForm.getId());
            wFlowFormSendBid.setSupplierId(wFlowFormSupplierEntry.getSupplierId());
            wFlowFormSendBid.setSegmentsNumber(wFlowFormSupplierEntry.getSegmentsNumber());
            wFlowFormSendBidService.insert(wFlowFormSendBid);
        }
    }

    /**
     * 更新外网显示状态 插入历史
     *
     * @param
     */
    void updateSendBidOuterStatus(String formId, String supplierId) {
        String extStatus = "";
        WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(formId, supplierId);
        extStatus += WFlowFormExtEnum.STATUS_3.getCode();
        wFlowFormExtMng.setFlowFormStatus(extStatus);
        wFlowFormExtMngService.updateById(wFlowFormExtMng);
        List<WFlowFormExtSubMng> subs = wFlowFormExtSubMngService.getByParentId(wFlowFormExtMng.getId());
        for (WFlowFormExtSubMng wFlowFormExtSubMng : subs) {
            SHistoryComment sHistoryComment = buildCommonHistory(formId, wFlowFormExtSubMng.getId(),
                    HistoryCommentModelTypeEnum.HistoryCommentModelType19.getCode(), "",
                    PurchaseActionNameEnum.PURCHASE_PLAN_7_1.getDesc(), PurchaseNodeEnum.NODE_7_1.getDesc(),
                    0, false);
            sHistoryComment.setActionStatus(PurchaseCommonEnum.OUTER_PROCESS_STATUS_1.getCode());
            sHistoryCommentService.insert(sHistoryComment);
        }
    }

    /**
     * 生成暗标编号
     */
    public void generateDarkCode(WFlowForm wFlowForm) {
        String codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        List<String> wFlowFormBackBids = wFlowFormBackBidService.selectSupplieridsWithBackBid(wFlowForm.getId());
        char[] code = new char[wFlowFormBackBids.size()];
        for (int i = 0; i < wFlowFormBackBids.size(); i++) {
            code[i] = codes.charAt(i);
        }
        char[] arrTemp = new char[wFlowFormBackBids.size()];
        int end = wFlowFormBackBids.size();
        Random rad = new Random();
        for (int i = 0; i < code.length; i++) {
            int index = rad.nextInt(end);
            arrTemp[i] = code[index];
            code[index] = code[end - 1];
            end--;
        }
        int i = 0;
        for (String supplierid : wFlowFormBackBids) {
            wFlowFormBackBidService.grenerateDarkCodeByFormIdAndSupplierId(arrTemp[i] + "", wFlowForm.getId(), supplierid);
            i++;
        }
    }

    /**
     * 更新询标后的技术评分
     */
    public void updateTechnologyScore(WFlowForm wFlowForm) {
        //DecimalFormat dFormat=new DecimalFormat("#.00");
        InquiringBidRspVO inquiringBidRspVO = selectInquiringBidNodeData(wFlowForm.getId());
        List<IdNameVO> suppliers = inquiringBidRspVO.getScores().getSuppliers();
        List<Double> scores = inquiringBidRspVO.getScores().getTotalWeightScore();
        int i = 0;
        List<SSuppliersCategoryTemplate> sSuppliersCategoryTemplateList = sSuppliersCategoryTemplateService.
                selectByCategoryIdAndTypes(wFlowForm.getPurchaseClassification(),
                        SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_BRIGHT_MARK.getCode(),
                        SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_DARK_MARK.getCode(),
                        SuppliersCategoryTemplateTypeEnum.SCORE_INTERVIEW_BY_MANAGER.getCode());
        Double total = 0d;
        for (SSuppliersCategoryTemplate s : sSuppliersCategoryTemplateList) {
            total += Double.valueOf(s.getScoreStandard());
        }
        for (IdNameVO s : suppliers) {
            boolean qu = scores.get(i) >= (total * 0.7);
            wFlowFormBackBidService.updateTechnicalScoreByFormIdAndSupplierId(wFlowForm.getId(), s.getId(), scores.get(i), qu);
            i++;
        }

    }

    /**
     * 保存询标节点数据
     */
    public void saveInquiringBidNodeData(WFlowForm wFlowForm) {
        List<WFlowFormPurchaseTeam> wFlowFormPurchaseTeams = wFlowFormPurchaseTeamService.
                getTeamByFlowFormIdAndJob(wFlowForm.getId(), PurchaseCommonEnum.PURCHASE_JOB_3.getCode(), PurchaseCommonEnum.PURCHASE_JOB_4.getCode());

        //List<WFlowFormSupplierEntry> wFlowFormSupplierEntrys = wFlowFormSupplierEntryService.getReplyAgreeByFormIdGroupBySupplier(wFlowForm.getId());
        List<String> suppliers = wFlowFormBackBidService.selectSupplieridsWithBackBid(wFlowForm.getId());
        for (WFlowFormPurchaseTeam w : wFlowFormPurchaseTeams) {
            for (String ws : suppliers) {

                WFlowFormIbTechScore wFlowFormIbTechScore = new ExtWFlowFormIbTechScore();
                wFlowFormIbTechScore.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                wFlowFormIbTechScore.setFlowFormId(wFlowForm.getId());
                wFlowFormIbTechScore.setSupplierId(ws);
                wFlowFormIbTechScore.setUserId(w.getUserId());
//					wFlowFormIbTechScore.setPmInterviewScore(0d);
//					wFlowFormIbTechScore.setTechnicalDarkScore(0d);
//					wFlowFormIbTechScore.setTechnicalScore(0d);
//					wFlowFormIbTechScore.setTotalScore(0d);
                wFlowFormIbTechScoreService.insert(wFlowFormIbTechScore);
            }
        }

    }

    /**
     * 完成采购计划节点-save next node data
     *
     * @param wFlowForm
     */
    public void savePPlanNextNodeData(WFlowForm wFlowForm) {
        String flowFormId = wFlowForm.getId();
        Integer qualified = CommonConstants.BID_NO;
        if (wFlowForm.getFlowType() == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_4.getCode() ||
                wFlowForm.getFlowType() == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_6.getCode()) {
            qualified = CommonConstants.BID_OK;
        }

        int sn = wFlowForm.getSegmentsNumber() == null ? 1 : wFlowForm.getSegmentsNumber();
        List<WFlowFormBidCandidateUnit> WFlowFormBidCandidateUnits = wFlowFormBidCandidateUnitService.selectList(
                new EntityWrapper<WFlowFormBidCandidateUnit>().eq("flow_form_id", flowFormId)
                        .eq("del_flag", CommonConstants.DEL_FLAG_NORMAL));
        if (CollectionUtils.isEmpty(WFlowFormBidCandidateUnits))
            throw new RuntimeException("无候选人", new ServiceThrowable());
        for (WFlowFormBidCandidateUnit w : WFlowFormBidCandidateUnits) {
            for (int i = 1; i <= sn; i++) {
                wFlowFormBackBidService.insert(buildWFlowFormBackBid(flowFormId, w.getSuppliersId(),
                        CommonConstants.AWARD_BID_NOT, qualified, i));
            }
//			for (int i = 1; i <= sn; i++) {
//				WFlowFormSupplierEntry wse = new WFlowFormSupplierEntry();
//				wse.setBaseFeilds(UserUtils.getCurrentUserId(), "",
//						CommonConstants.DEL_FLAG_NORMAL, true);
//				wse.setFlowFormId(flowFormId);
//				wse.setSupplierId(w.getSuppliersId());
//				wse.setSegmentsNumber(i);
//				wFlowFormSupplierEntryService.insert(wse);
//			}
        }
    }

    /**
     * 完成供应商入围-save next node data
     *
     * @param wFlowForm
     */
    public void saveSupplierEntryNextNodeData(WFlowForm wFlowForm) {
        List<WFlowFormSupplierEntry> wFlowFormSupplierEntrys = wFlowFormSupplierEntryService.getByFormId(wFlowForm.getId());
        if (CollectionUtils.isEmpty(wFlowFormSupplierEntrys))
            throw new RuntimeException("无供应商参与", new ServiceThrowable());
        Set<String> sets = new HashSet<>();//记录没有操作的供应商
        for (WFlowFormSupplierEntry w : wFlowFormSupplierEntrys) {
            if (w.getReplySituation() == null)
                sets.add(w.getSupplierId());
            else if (w.getReplySituation() == CommonConstants.SUPPLIER_RESPONSE_LETTER_YES) {
                WFlowFormBackBid wFlowFormBackBid = buildWFlowFormBackBid(wFlowForm.getId(), w.getSupplierId(),
                        CommonConstants.AWARD_BID_NOT, CommonConstants.BID_NO, w.getSegmentsNumber());
                if (wFlowForm.getFlowType() == PurchasePlanFlowTypeEnum.PURCHASE_FLOW_TYPE_1.getCode()) {
                    wFlowFormBackBid.setQualificationOrNot(CommonConstants.BID_OK);
                }
                wFlowFormBackBidService.insert(wFlowFormBackBid);
            }
        }

        for (String supplierId : sets) {
            SMyDeals sMyDeals = new SMyDeals();
            sMyDeals.setActionType(MyDealActionTypeEnum.PPLAN_INVITATION_OUT.getCode());
            sMyDeals.setDealSubType(MyDealSubTypeEnum.SUPPLIER_ENTRY.getCode());
            sMyDeals.setRelatedId(wFlowForm.getId());
            sMyDeals.setUserId(supplierId);
            sMyDealsService.doneByEntityAndUsers(sMyDeals, null, "未回复");
            WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(wFlowForm.getId(), supplierId);

            wFlowFormExtMng.setFlowFormSubStatus(WFlowFormExtSubEnum.STATUS_1_3.getCode() + "");
            wFlowFormExtMngService.updateById(wFlowFormExtMng);
            for (WFlowFormExtSubMng wFlowFormExtSubMngs : wFlowFormExtSubMngService.getByParentId(wFlowFormExtMng.getId())) {
                SHistoryComment sHistoryComment = buildCommonHistory(wFlowForm.getId(), wFlowFormExtSubMngs.getId(),
                        HistoryCommentModelTypeEnum.HistoryCommentModelType18.getCode(), "未回复",
                        PurchaseActionNameEnum.PURCHASE_PLAN_5_4.getDesc(), PurchaseNodeEnum.NODE_5_1.getDesc(), 0, false);
                sHistoryComment.setActionStatus(PurchaseCommonEnum.OUTER_PROCESS_STATUS_2.getCode());
                sHistoryCommentService.saveSHistoryComment(sHistoryComment);
            }
        }

    }


    /**
     * 答疑／补遗 节点数据
     *
     * @param wFlowForm
     */
    public void saveWflowFormQuestionAnswer(WFlowForm wFlowForm) {
        List<WFlowFormBackBid> wFlowFormBackBids = wFlowFormBackBidService.getByFormId(wFlowForm.getId());
        for (WFlowFormBackBid w : wFlowFormBackBids) {
            if (w.getSendBidStatus() == 1) {
                WFlowFormQuestionAnswer wFlowFormQuestionAnswer = new WFlowFormQuestionAnswer();
                wFlowFormQuestionAnswer.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                wFlowFormQuestionAnswer.setFlowFormId(w.getFlowFormId());
                wFlowFormQuestionAnswer.setSegmentsNumber(w.getSegmentsNumber());
                wFlowFormQuestionAnswer.setSupplierId(w.getSupplierId());
                wFlowFormQuestionAnswer.setAddendumReferers(PurchaseCommonEnum.ATTACH_READED_NOT.getCode());
                wFlowFormQuestionAnswer.setSupplierReferers(PurchaseCommonEnum.ATTACH_READED_NOT.getCode());
                wFlowFormQuestionAnswerService.insert(wFlowFormQuestionAnswer);
            }

        }
    }

    /**
     * 定标审批通过
     *
     * @param formId
     */
    public void saveAndUpdateCalibratedBidData(String formId) {
        WFlowForm wFlowForm = wFlowFormService.selectById(formId);
        List<ExtWFlowFormBackBid> wFlowFormBackBids = wFlowFormBackBidService.getExtBackBidByFormId(formId);
        SMessageTemplate sMessageTemplate = sMessageTemplateService.getByMsgType(MessagesMsgTypeEnum.MsgType11.getCode());
        for (ExtWFlowFormBackBid w : wFlowFormBackBids) {
            WFlowFormBidNoticeThanks wFlowFormBidNoticeThanks = new WFlowFormBidNoticeThanks();
            wFlowFormBidNoticeThanks.setFlowFormId(formId);
            wFlowFormBidNoticeThanks.setSupplierId(w.getSupplierId());
            wFlowFormBidNoticeThanks.setSegmentsNumber(w.getSegmentsNumber());
            wFlowFormBidNoticeThanks.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);

            if (w.getAwardBidOrNot() == CommonConstants.YES_INTEGER) {//中标
                wFlowFormBidNoticeThanks.setNoticeType(PurchaseCommonEnum.NOTICE_TYPE.getCode());
            } else {
                wFlowFormBidNoticeThanks.setNoticeContent(MessageFormat.format(sMessageTemplate.getMsgContent(), wFlowForm.getPurchaseItemName()));
                wFlowFormBidNoticeThanks.setNoticeType(PurchaseCommonEnum.THANK_TYPE.getCode());
            }
            wFlowFormBidNoticeThanksService.insert(wFlowFormBidNoticeThanks);
        }

    }

    /**
     * 流标更新状态
     *
     * @param wFlowForm
     */
    public void abortiveDataHandle(WFlowForm wFlowForm, int status) {
        WFlowForm w = new WFlowForm();
        w.setId(wFlowForm.getId());
        w.setAbortiveAuditedTime(DateUtils.getNow());
        w.setAbortiveFlag(status);

        wFlowFormService.updateById(w);
    }


    /**
     * 到达入围需要的数据
     */
    public void saveInvitationNextnodeData(WFlowForm wFlowForm) {
        List<WFlowFormBidCandidateUnit> wFlowFormBidCandidateUnits = wFlowFormBidCandidateUnitService.getByFormId(wFlowForm.getId());
        int sn = wFlowForm.getSegmentsNumber() == null ? 1 : wFlowForm.getSegmentsNumber();
        SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.PURCHASE_INVITATION_DEAL.getCode());
        String title = MessageFormat.format(sc.getConfigValue(), wFlowForm.getPurchaseItemName());
        for (WFlowFormBidCandidateUnit w : wFlowFormBidCandidateUnits) {
            //外网招标管理-主列表
            WFlowFormExtMng wFlowFormExtMng = new WFlowFormExtMng();
            wFlowFormExtMng.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
            wFlowFormExtMng.setFlowFormId(w.getFlowFormId());
            wFlowFormExtMng.setFormTitle(wFlowForm.getPurchaseItemName());
            wFlowFormExtMng.setFlowFormStatus(WFlowFormExtEnum.STATUS_1.getCode() + "");
            wFlowFormExtMng.setFlowFormSubStatus(WFlowFormExtSubEnum.STATUS_1_1.getCode() + "");
            wFlowFormExtMng.setUserId(w.getSuppliersId());
            wFlowFormExtMngService.insert(wFlowFormExtMng);
            for (int i = 1; i <= sn; i++) {
                //入围预制数据
                WFlowFormSupplierEntry wse = new WFlowFormSupplierEntry();
                wse.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                wse.setFlowFormId(wFlowForm.getId());
                wse.setSupplierId(w.getSuppliersId());
                wse.setSegmentsNumber(i);
                wFlowFormSupplierEntryService.insert(wse);

                //外网招标管理-从数据
                WFlowFormExtSubMng wFlowFormExtSubMng = new WFlowFormExtSubMng();
                wFlowFormExtSubMng.setFlowFormExtMngId(wFlowFormExtMng.getId());
                wFlowFormExtSubMng.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                wFlowFormExtSubMng.setFlowFormId(w.getFlowFormId());
                wFlowFormExtSubMng.setSegmentsNumber(i);
                wFlowFormExtSubMng.setActionStatus(WFlowFormExtSubEnum.STATUS_4_1.getCode());
                wFlowFormExtSubMngService.insert(wFlowFormExtSubMng);

            }
            //邀请函代办
            sMyDealsService.insert(buildCommonDeals(wFlowForm.getId(), wFlowForm.getId(),
                    MyDealSubTypeEnum.SUPPLIER_ENTRY.getCode(),
                    MyDealActionTypeEnum.PPLAN_INVITATION_OUT.getCode(),
                    title,
                    w.getSuppliersId(), null, null));

            //保证金确认预制数据
            WFlowFormCashDeposit wFlowFormCashDeposit = new WFlowFormCashDeposit();
            wFlowFormCashDeposit.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
            wFlowFormCashDeposit.setFlowFormId(wFlowForm.getId());
            wFlowFormCashDeposit.setSupplierId(w.getSuppliersId());
            wFlowFormCashDeposit.setBidBonds(wFlowForm.getBidBounds());
            wFlowFormCashDepositService.insert(wFlowFormCashDeposit);
        }
    }

    /**
     * 获取入围供应商列表(待办入口)
     */
    @Override
    public RestReturnResult lstSupplierEntry(String flowFormId) throws Exception {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, flowFormId, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);
        try {

            if (StringUtils.isNotEmpty(flowFormId)) {

                //获取采购待办记录
                //SMyDeals sMyDeals = sMyDealsService.selectUntreatedById(myDealId);

                Map<Integer, List<ExtWFlowFormSupplierEntry>> resultMap = new HashMap<Integer, List<ExtWFlowFormSupplierEntry>>();
                FlowFormSupplierEntryListResponseVO result = new FlowFormSupplierEntryListResponseVO();
                if (flowFormId != null) {
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("flowFormId", flowFormId);
                    List<ExtWFlowFormSupplierEntry> wFlowFormSupplierEntryList = wFlowFormSupplierEntryService.getFlowFormSupplierEntryList(param);

                    if (wFlowFormSupplierEntryList != null && wFlowFormSupplierEntryList.size() > 0) {
                        for (ExtWFlowFormSupplierEntry supplierEntry : wFlowFormSupplierEntryList) {
                            if (resultMap.containsKey(supplierEntry.getSegmentsNumber())) {
                                List<ExtWFlowFormSupplierEntry> list = resultMap.get(supplierEntry.getSegmentsNumber());
                                list.add(supplierEntry);
                                resultMap.put(supplierEntry.getSegmentsNumber(), list);
                            } else {
                                List<ExtWFlowFormSupplierEntry> list = new ArrayList<ExtWFlowFormSupplierEntry>();
                                list.add(supplierEntry);
                                resultMap.put(supplierEntry.getSegmentsNumber(), list);
                            }
                        }


                        restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, resultMap);
                    } else {
                        restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
                    }

                } else {
                    restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
                }

            } else {
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-------lstSuppliersEntry-------e-----:" + e.getMessage());
            throw new Exception(e);
        }

        return restResult;

    }

    /**
     * 发起保证金确认
     */
    @Override
    public RestReturnResult launchDepositConfirm(String flowFormId) throws Exception {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, flowFormId, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        try {

            if (StringUtils.isNotEmpty(flowFormId)) {

                Map<String, Object> param = new HashMap<String, Object>();
                param.put("flowFormId", flowFormId);

                List<ExtWFlowFormCashDeposit> list = wFlowFormCashDepositService.selectDepositConfirmBidList(param);
//				if(list == null){//初始化
//					list = wFlowFormCashDepositService.selectDepositConfirmBidCandidateUnitList(param);
//				}

                List<DepositConfirmBidCandidateUnitResponseVO> resultList = ListObjCopyUtil.copyTo(list, DepositConfirmBidCandidateUnitResponseVO.class);

                restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, resultList);
            } else {
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-------launchDepositConfirm-------e-----:" + e.getMessage());
            throw new Exception(e);
        }

        return restResult;
    }


    private WFlowFormCashDeposit getEntityByDepositConfirmRequestVO(DepositConfirmRequestEntity vo, boolean isAdded) {
        WFlowFormCashDeposit result = null;

        if (vo != null) {
            result = new WFlowFormCashDeposit();

            Date date = new Date();
            String userId = UserUtils.getCurrentUserId();

            if (isAdded) {
                result.setId(IdGenUtils.uuid());
                result.setCreateBy(userId);
                result.setCreateDate(date);
            } else {
                result.setId(vo.getId());
            }

            result.setUpdateBy(userId);
            result.setUpdateDate(date);
            result.setDelFlag(CommonConstants.NO_INTEGER);

            result.setFlowFormId(vo.getFlowFormId());
            result.setSupplierId(vo.getSupplierId());
            result.setBidBonds(vo.getBidBonds());
            result.setConfirmedBidBonds(vo.getConfirmedBidBonds());
            result.setBidBoundDesc(vo.getBidBoundDesc());
            result.setCashierConfirmStatus(vo.getCashierConfirmStatus());
        }

        return result;
    }


    /**
     * 模拟MBS回调
     *
     * @param purchaseMbsCallBackVO
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public void purchaseMbsCallBack(PurchaseMbsCallBackVO purchaseMbsCallBackVO) {
        try {
            WFlowSubForm wFlowSubForm = wFlowSubFormService.selectByFormId(purchaseMbsCallBackVO.getFlowFormId());
            SHistoryComment sHistoryComment = new SHistoryComment();
            sHistoryComment.setBaseFeilds(UserUtils.getCurrentUserId(), "",
                    CommonConstants.DEL_FLAG_NORMAL, true);
            sHistoryComment.setAgreeFlag(purchaseMbsCallBackVO.getAgreeFlag());
            sHistoryComment.setCommentContent(purchaseMbsCallBackVO.getComments());
            Integer modelType = null;
            String nodeName = "";
            boolean dingbidAgree = false;
            if (purchaseMbsCallBackVO.getAbutmentSubType() == AbutmentSubTypeEnum.LINE_STATUS_PURCHASE_SCHEME.getCode()) {
                nodeName = sCommentConfigService.getValueByCode(CommentConfigEnum.P_PLAN_NODE_NAME_HISTORY_DONE.getCode());
                modelType = HistoryCommentModelTypeEnum.HistoryCommentModelType7.getCode();
                wFlowSubForm.setPurchaseSolutionActionTime(DateUtils.getNow());
                if (purchaseMbsCallBackVO.getAgreeFlag() == CommonConstants.NO_AGREE_FLAG) {
                    wFlowSubForm.setPurchaseSolutionStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_1_STATUS_1.getCode());
                } else {
                    wFlowSubForm.setPurchaseSolutionStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_1_STATUS_3.getCode());
                }
            } else if (purchaseMbsCallBackVO.getAbutmentSubType() == AbutmentSubTypeEnum.LINE_STATUS_BID_DOC.getCode()) {
                nodeName = sCommentConfigService.getValueByCode(CommentConfigEnum.P_DOC_NODE_NAME_HISTORY_DONE.getCode());
                modelType = HistoryCommentModelTypeEnum.HistoryCommentModelType8.getCode();
                wFlowSubForm.setBidDocActionTime(DateUtils.getNow());
                if (purchaseMbsCallBackVO.getAgreeFlag() == CommonConstants.NO_AGREE_FLAG) {
                    wFlowSubForm.setBidDocStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_3_STATUS_1.getCode());
                } else {
                    wFlowSubForm.setBidDocStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_3_STATUS_3.getCode());
                }
            } else if (purchaseMbsCallBackVO.getAbutmentSubType() == AbutmentSubTypeEnum.LINE_STATUS_CALIBRATION_BID.getCode()) {
                nodeName = sCommentConfigService.getValueByCode(CommentConfigEnum.P_DINGBID_NODE_NAME_HISTORY_DONE.getCode());
                modelType = HistoryCommentModelTypeEnum.HistoryCommentModelType11.getCode();
                wFlowSubForm.setCalibrationBidTime(DateUtils.getNow());
                if (purchaseMbsCallBackVO.getAgreeFlag() == CommonConstants.NO_AGREE_FLAG) {
                    wFlowSubForm.setCalibrationBidStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_12_STATUS_1.getCode());
                } else {
                    wFlowSubForm.setCalibrationBidStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_12_STATUS_4.getCode());
                    saveAndUpdateCalibratedBidData(purchaseMbsCallBackVO.getFlowFormId());
                    dingbidAgree = true;

                }
            }

            sHistoryComment.setModelType(modelType);
            sHistoryComment.setRelatedId(purchaseMbsCallBackVO.getFlowFormId());
            if (StringUtils.isNotEmpty(purchaseMbsCallBackVO.getRcRelatedId())) {
                sHistoryComment.setSubRelatedId(purchaseMbsCallBackVO.getRcRelatedId());
            } else {
                sHistoryComment.setSubRelatedId(purchaseMbsCallBackVO.getFlowFormId());
            }
            sHistoryComment.setNodeName(nodeName);
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
            sHistoryComment.setActionName(purchaseMbsCallBackVO.getAgreeFlag() == CommonConstants.NO_AGREE_FLAG ? "不同意" : "同意");
            sHistoryComment.setCommentUrl(purchaseMbsCallBackVO.getAbutmentDetailUrl());

            wFlowSubFormService.updateById(wFlowSubForm);
            sHistoryCommentService.saveSHistoryComment(sHistoryComment);
            updateWfformMbsStatus(purchaseMbsCallBackVO.getFlowFormId(), WFlowFormStatusEnum.MBS_BPM_FLAG_3.getCode());

            if (dingbidAgree) {
                FlowTurnVO flowTurnVO = new FlowTurnVO();
                flowTurnVO.setFlowFormId(purchaseMbsCallBackVO.getFlowFormId());
                flowTurnVO.setGoFlag(1);
                flowTurnVO.setNodeCode(WorkFlowLineStatusEnum.LINE_STATUS_CALIBRATION_BID.getCode());
                FlowTurnCommon(flowTurnVO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }


    /**
     * mbs回调处理方法
     *
     * @param mbsCommonCallBackReqVO
     * @param mbsCommonCallBackReqVOList
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void purchaseMbsCallBack(MbsCommonCallBackReqVO mbsCommonCallBackReqVO, List<MbsCommonCallBackReqVO> mbsCommonCallBackReqVOList) {
        if (StringUtils.isNotEmpty(mbsCommonCallBackReqVO.getUrl()))
            mbsCommonCallBackReqVO.setUrl(Encodes.decodeBase64String(mbsCommonCallBackReqVO.getUrl()));
        Integer modelType = null;
        String nodeName = "";
        boolean dingbidAgree = false;
        Integer agree = mbsCommonCallBackReqVO.getStatus().equalsIgnoreCase("PASS") ? CommonConstants.AGREE_FLAG : CommonConstants.NO_AGREE_FLAG;
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();

        WFlowSubForm wFlowSubForm = wFlowSubFormService.selectByFormId(mbsCommonCallBackReqVO.getUuid());


        ////操作人信息
        String userId = null;
        if (StringUtils.isNotEmpty(mbsCommonCallBackReqVO.getUser_code())) {
            SysUser sysUser = sysUserService.selectById(mbsCommonCallBackReqVO.getUser_code());
            if (sysUser == null) {
                sysUser = new SysUser();
                sysUser.setPassword(DigestUtils.md5Hex("abc123456"));//默认abc123456
                sysUser.setUserType(CommonConstants.INNER_USER);
                sysUser.setLoginFlag(CommonConstants.YES_LOGIN);
                sysUser.setId(mbsCommonCallBackReqVO.getUser_code());
                sysUser.setLoginName(mbsCommonCallBackReqVO.getUser_code());
                sysUser.setUserCode(mbsCommonCallBackReqVO.getUser_code());
                sysUser.setName(mbsCommonCallBackReqVO.getUser_name());
                sysUser.setBaseFeilds(UserUtils.getCurrentUserId(), null, 0, true);
                sysUserService.insert(sysUser);
            }
            userId = sysUser.getId();
        }

        ///
        SHistoryComment sHistoryComment = new SHistoryComment();
        sHistoryComment.setBaseFeilds(userId, "", CommonConstants.DEL_FLAG_NORMAL, true);
        sHistoryComment.setAgreeFlag(agree);
        sHistoryComment.setCommentContent(mbsCommonCallBackReqVO.getContent());
        sHistoryComment.setCommentUrl(mbsCommonCallBackReqVO.getUrl());

        Integer type = null;
        if (StringUtils.equalsIgnoreCase(mbsCommonCallBackReqVO.getType(), MBSCommonTypeEnum.MBSCommonTypeEnum_SourcingCandidate.getCode())) {
            nodeName = sCommentConfigService.getValueByCode(CommentConfigEnum.P_PLAN_NODE_NAME_HISTORY_DONE.getCode());
            modelType = HistoryCommentModelTypeEnum.HistoryCommentModelType7.getCode();
            wFlowSubForm.setPurchaseSolutionActionTime(DateUtils.getNow());
            if (agree == CommonConstants.NO_AGREE_FLAG) {
                wFlowSubForm.setPurchaseSolutionStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_1_STATUS_1.getCode());
            } else {
                wFlowSubForm.setPurchaseSolutionStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_1_STATUS_3.getCode());
            }
            type = CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_5.getCode();
        } else if (StringUtils.equalsIgnoreCase(mbsCommonCallBackReqVO.getType(), MBSCommonTypeEnum.MBSCommonTypeEnum_SourcingFile.getCode())) {
            nodeName = sCommentConfigService.getValueByCode(CommentConfigEnum.P_DOC_NODE_NAME_HISTORY_DONE.getCode());
            modelType = HistoryCommentModelTypeEnum.HistoryCommentModelType8.getCode();
            wFlowSubForm.setBidDocActionTime(DateUtils.getNow());
            if (agree == CommonConstants.NO_AGREE_FLAG) {
                wFlowSubForm.setBidDocStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_3_STATUS_1.getCode());
            } else {
                wFlowSubForm.setBidDocStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_3_STATUS_3.getCode());
            }
            type = CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_6.getCode();
        } else if (StringUtils.equalsIgnoreCase(mbsCommonCallBackReqVO.getType(), MBSCommonTypeEnum.MBSCommonTypeEnum_SourcingDecision.getCode())) {
            nodeName = sCommentConfigService.getValueByCode(CommentConfigEnum.P_DINGBID_NODE_NAME_HISTORY_DONE.getCode());
            modelType = HistoryCommentModelTypeEnum.HistoryCommentModelType11.getCode();
            wFlowSubForm.setCalibrationBidTime(DateUtils.getNow());
            if (agree == CommonConstants.NO_AGREE_FLAG) {
                wFlowSubForm.setCalibrationBidStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_12_STATUS_1.getCode());
            } else {
                wFlowSubForm.setCalibrationBidStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_12_STATUS_4.getCode());
                saveAndUpdateCalibratedBidData(mbsCommonCallBackReqVO.getUuid());
                dingbidAgree = true;

            }
            type = CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_7.getCode();
        }

        sHistoryComment.setModelType(modelType);
        sHistoryComment.setRelatedId(mbsCommonCallBackReqVO.getUuid());
        if (StringUtils.isNotEmpty(mbsCommonCallBackReqVO.getSdId())) {
            sHistoryComment.setSubRelatedId(mbsCommonCallBackReqVO.getSdId());
        } else {
            sHistoryComment.setSubRelatedId(mbsCommonCallBackReqVO.getUuid());
        }
        sHistoryComment.setNodeName(nodeName);
        sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
        sHistoryComment.setActionName(agree == CommonConstants.NO_AGREE_FLAG ? "不同意" : "同意");

        wFlowSubFormService.updateById(wFlowSubForm);
        sHistoryCommentService.saveSHistoryComment(sHistoryComment);
        updateWfformMbsStatus(mbsCommonCallBackReqVO.getUuid(), WFlowFormStatusEnum.MBS_BPM_FLAG_3.getCode());

        sAbutmentLogsService.saveAbutmentLogs(type, mbsCommonCallBackReqVO.getUuid(), gson.toJson(mbsCommonCallBackReqVOList), 1, 0);
        if (dingbidAgree) {
            FlowTurnVO flowTurnVO = new FlowTurnVO();
            flowTurnVO.setFlowFormId(mbsCommonCallBackReqVO.getUuid());
            flowTurnVO.setGoFlag(1);
            flowTurnVO.setNodeCode(WorkFlowLineStatusEnum.LINE_STATUS_CALIBRATION_BID.getCode());
            FlowTurnCommon(flowTurnVO);
        }
    }

    /**
     * 保证金确认
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult depositConfirm(DepositConfirmRequestVO depositConfirmRequestVO) throws RuntimeException {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        try {

            if (depositConfirmRequestVO != null
                    && depositConfirmRequestVO.getDepositConfirmRequestList() != null
                    && depositConfirmRequestVO.getDepositConfirmRequestList().size() > 0) {

                List<WFlowFormCashDeposit> saveList = new ArrayList<WFlowFormCashDeposit>();
                List<WFlowFormCashDeposit> updateList = new ArrayList<WFlowFormCashDeposit>();
                List<DepositConfirmRequestEntity> checkByFlowList = new ArrayList<DepositConfirmRequestEntity>();

                List<DepositConfirmRequestEntity> depositConfirmRequestList =
                        depositConfirmRequestVO.getDepositConfirmRequestList();


                for (DepositConfirmRequestEntity vo : depositConfirmRequestList) {
                    WFlowFormCashDeposit entity = null;

                    if (vo.getCashierConfirmStatus() != null
                            && (vo.getCashierConfirmStatus() == CashierConfirmStatusEnum.CONFIRMED.getCode()
                            || vo.getCashierConfirmStatus() == CashierConfirmStatusEnum.CONFIRMING.getCode())) {

                    } else {
                        if (depositConfirmRequestVO.getActionType() == 2
                                && vo.getSelected() == CommonConstants.YES_INTEGER) { //提交出纳确认 && 被选中的，需走对接流程
                            checkByFlowList.add(vo);

                            //确认中
//                            vo.setCashierConfirmStatus(CashierConfirmStatusEnum.CONFIRMING.getCode());
                            //经办人提交时，直接做已确认处理，不再从财务出纳系统更新。
                            vo.setCashierConfirmStatus(CashierConfirmStatusEnum.CONFIRMED.getCode());
                        }

                        if (StringUtils.isNotEmpty(vo.getId())) { // update
                            entity = this.getEntityByDepositConfirmRequestVO(vo, false);
                            updateList.add(entity);
                        } else { //insert
                            entity = this.getEntityByDepositConfirmRequestVO(vo, true);
                            saveList.add(entity);
                        }

                    }

                }

                //对接MBS保证金接口
                if (checkByFlowList != null && checkByFlowList.size() > 0) {
                    //筑科暂时没有财务确认动作， 不同步到财务出纳系统，经办人操作时直接做已确认处理
//                    this.dealMBSToDoList(checkByFlowList, "A");
                }


                //保存或更新 供应商入围-保证金确认记录
                if (saveList != null && saveList.size() > 0) {
                    wFlowFormCashDepositService.insertBatch(saveList);
                }

                if (updateList != null && updateList.size() > 0) {
                    wFlowFormCashDepositService.updateBatchById(updateList);
                }


                restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS);
            } else {
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-------depositConfirm-------e-----:" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

        return restResult;
    }

    /**
     * 下发投标保证金处理
     *
     * @param toDoList
     * @param sdStatus A收   C退
     * @return
     */
    private boolean dealMBSToDoList(List<DepositConfirmRequestEntity> toDoList, String sdStatus) {

        if (toDoList != null && toDoList.size() > 0) {
            Date createDate = new Date();
            List<SynSourcingDepositDataVo> synSupplierDataVoList = new ArrayList<SynSourcingDepositDataVo>();

            for (DepositConfirmRequestEntity entity : toDoList) {

                SynSourcingDepositDataVo vo = new SynSourcingDepositDataVo();
                WFlowForm wFlowForm = wFlowFormService.selectById(entity.getFlowFormId());
                if (wFlowForm != null) {
                    vo.setSdSrId(wFlowForm.getContractId());
                }

                WFlowFormBidCandidateUnit wFlowFormBidCandidateUnit = wFlowFormBidCandidateUnitService.getBidCandidateUnitByFormIdAndSupplierId(entity.getFlowFormId(), entity.getSupplierId());
                if (wFlowFormBidCandidateUnit != null) {
                    vo.setSdSciId(wFlowFormBidCandidateUnit.getId());
                }

                SSuppliers sSuppliers = sSuppliersService.selectById(entity.getSupplierId());
                if (sSuppliers != null) {
                    vo.setSdSrName(sSuppliers.getCompanyName());
                }

                SCompany sCompany = sCompanyService.selectById(entity.getCompanyId());
                if (sCompany != null) {
                    vo.setSdCompanyCode(sCompany.getCompanyCode());
                    vo.setSdCompanyName(sCompany.getCompanyName());
                }

                vo.setSdMoney(entity.getConfirmedBidBonds());
//				vo.setSdRemark("setting bidBonds is " + entity.getBidBonds());
                vo.setSdStatus(sdStatus);// A收   C退
                vo.setSdUserName(UserUtils.getCurrentUserId());
                vo.setSdCreateDate(DateUtils.format(createDate, "yyyy-MM-dd hh:mm:ss"));
                vo.setSdServiceUuid(entity.getId());
                synSupplierDataVoList.add(vo);
            }

            if (synSupplierDataVoList != null && synSupplierDataVoList.size() > 0) {
                return synDataService.invokeSourcingDeposit(synSupplierDataVoList);
            }
        }

        return false;
    }

    /**
     * 招标公告
     */
    @Override
    public RestReturnResult biddingAnnouncement(String flowFormId) throws Exception {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        try {

            if (StringUtils.isNotEmpty(flowFormId)) {

//				SMessageTemplate param = new SMessageTemplate();
//				param.setMsgType(MessagesMsgTypeEnum.MsgType2.getCode());
//				EntityWrapper<SMessageTemplate> wrapper = new EntityWrapper<SMessageTemplate>();
//				wrapper.setEntity(param);
//				SMessageTemplate sMessageTemplate = sMessageTemplateService.selectOne(wrapper);

                BiddingAnnouncementResponseVO result = new BiddingAnnouncementResponseVO();

                WFlowForm wFlowForm = wFlowFormService.selectById(flowFormId);

                if (wFlowForm != null/* && sMessageTemplate != null*/) {
                    result.setPurchaseItemName(wFlowForm.getPurchaseItemName());
                    SProject project = sProjectService.selectById(wFlowForm.getProjectId());
                    if (project != null) {
                        result.setProjectName(project.getProjectName());
                    }
                    result.setProjectLocation(wFlowForm.getProjectLocation());
                    result.setBiddingContent(wFlowForm.getPurchaseRange());

                    SSuppliersCategory sSuppliersCategory = sSuppliersCategoryService.selectById(wFlowForm.getPurchaseClassification());
                    if (sSuppliersCategory != null) {
                        result.setBiddingCategory(sSuppliersCategory.getCategoryName());
                    }
                    if (StringUtils.isNotEmpty(wFlowForm.getPurchaseCategoryId())) {
                        SStrategicCategory sStrategicCategory = sStrategicCategoryService.selectById(wFlowForm.getPurchaseCategoryId());
                        if (sStrategicCategory != null) {
                            result.setCategoryUnit(sStrategicCategory.getCategoryUnit());
                        }
                    }

                    result.setProjectScale(wFlowForm.getProjectScale());
                    result.setPurchasedAmount(wFlowForm.getPurchasedAmount());
                    result.setSignedYears(wFlowForm.getSignedYears());
                    result.setEntryConditions(wFlowForm.getEntryConditions());
                    result.setContactInformation(sCommentConfigService.getValueByCode(CommentConfigEnum.BIDDING_ANNOUNCEMENT_CONTACT_INFORMATION.getCode()));

//					String announcementName = MessageFormat.format(sMessageTemplate.getMsgName(), wFlowForm.getPurchaseItemName());
//					String announcementContent = MessageFormat.format(sMessageTemplate.getMsgContent(), null, wFlowForm.getPurchaseRange(),
//							wFlowForm.getPurchaseRange(), wFlowForm.getPurchasedAmount(), wFlowForm.getSignedYears(), wFlowForm.getEntryConditions(),
//							sCommentConfigService.getValueByCode(CommentConfigEnum.BIDDING_ANNOUNCEMENT_CONTACT_INFORMATION.getCode()));
                    result.setFlowFormId(flowFormId);
//					result.setAnnouncementName(announcementName);
//					result.setAnnouncementContent(announcementContent);

                    restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, result);
                } else {//数据不存在
                    restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
                }

            } else {//传参为空
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-------biddingAnnouncement-------e-----:" + e.getMessage());
            throw new RuntimeException(e);
        }

        return restResult;
    }

    /**
     * 发送招标公告
     */
    @Override
    public RestReturnResult sendBiddingAnnoucement(BiddingAnnouncementRequestVO biddingAnnouncementRequestVO) {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        try {

            if (biddingAnnouncementRequestVO != null) {
                SMessages sMessage = new SMessages();
                sMessage.setMsgType(MessagesMsgTypeEnum.MsgType2.getCode());

                String titleTemplate = sCommentConfigService.getValueByCode(CommentConfigEnum.BIDDING_ANNOUNCEMENT_TITLE.getCode());
                WFlowForm wFlowForm = wFlowFormService.selectById(biddingAnnouncementRequestVO.getFlowFormId());

                if (wFlowForm != null) {
                    sMessage.setMsgTitle(MessageFormat.format(titleTemplate, wFlowForm.getPurchaseItemName()));
                    sMessage.setBidCategoryId(wFlowForm.getPurchaseClassification());
                } else {
                    throw new RuntimeException("采购流程不存在", new ServiceThrowable());
                }

                sMessage.setFlowFormId(biddingAnnouncementRequestVO.getFlowFormId());
                sMessagesService.addSMessages(sMessage);

                WFlowSubForm wFlowSubForm = new WFlowSubForm();
                wFlowSubForm.setFlowFormId(biddingAnnouncementRequestVO.getFlowFormId());
                wFlowSubForm.setSendBidNoticeFlag(CommonConstants.YES_INTEGER);
                wFlowSubFormService.updateByFormId(wFlowSubForm);

                restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS);
            } else {
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-------sendBiddingAnnoucement-------e-----:" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

        return restResult;
    }

    /**
     * 招标文件
     */
    @Override
    public RestReturnResult biddingDocument(String flowFormId) throws Exception {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);
        try {
            if (StringUtils.isNotEmpty(flowFormId)) {
                ExtWFlowForm extWFlowForm = wFlowFormService.getBiddingDocumentBaseInfoByFlowFormId(flowFormId);
                if (extWFlowForm != null) {

                    //招标文件基本信息
                    BiddingDocumentResponseVO result = new BiddingDocumentResponseVO();

                    result.setFlowForm(wFlowFormService.getExtByFormId(flowFormId));
                    result.setFlowSubForm(wFlowSubFormService.selectByFormId(flowFormId));
                    BeanUtils.copyProperties(extWFlowForm, result);

                    //招标文件附件
                    List<SAttachment> list1 = sAttachmentService.getByFormIdAndAttachmentType(flowFormId,
                            AttachmentTypeEnum.ATTACHMENT_TYPE_16.getCode(), AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                    List<AttachmentVO> biddingDocumentAttachmentList = ListObjCopyUtil.copyTo(list1, AttachmentVO.class);
                    result.setBiddingDocumentAttachmentList(biddingDocumentAttachmentList);


                    //图纸附件
                    List<SAttachment> list2 = sAttachmentService.getByFormIdAndAttachmentType(flowFormId,
                            AttachmentTypeEnum.ATTACHMENT_TYPE_17.getCode(), AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                    List<AttachmentVO> drawingAttachmentList = ListObjCopyUtil.copyTo(list2, AttachmentVO.class);
                    result.setDrawingAttachmentList(drawingAttachmentList);

                    //技术要求和管理要求附件
                    List<SAttachment> list3 = sAttachmentService.getByFormIdAndAttachmentType(flowFormId,
                            AttachmentTypeEnum.ATTACHMENT_TYPE_18.getCode(), AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                    List<AttachmentVO> techAndManageRequirementAttachmentList = ListObjCopyUtil.copyTo(list3, AttachmentVO.class);
                    result.setTechAndManageRequirementAttachmentList(techAndManageRequirementAttachmentList);

                    //其他附件
                    List<SAttachment> list4 = sAttachmentService.getByFormIdAndAttachmentType(flowFormId,
                            AttachmentTypeEnum.ATTACHMENT_TYPE_19.getCode(), AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                    List<AttachmentVO> otherAttachmentList = ListObjCopyUtil.copyTo(list4, AttachmentVO.class);
                    result.setOtherAttachmentList(otherAttachmentList);

                    //招标文件清单附件
                    List<SAttachment> list5 = sAttachmentService.getByFormIdAndAttachmentType(flowFormId,
                            AttachmentTypeEnum.ATTACHMENT_TYPE_46.getCode(), AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                    List<AttachmentVO> formAttachmentList = ListObjCopyUtil.copyTo(list5, AttachmentVO.class);
                    result.setFormAttachmentList(formAttachmentList);

                    //招标文件清单附件
                    List<SAttachment> list6 = sAttachmentService.getByFormIdAndAttachmentType(flowFormId,
                            AttachmentTypeEnum.ATTACHMENT_TYPE_100.getCode(), AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                    List<AttachmentVO> addAttachmentList = ListObjCopyUtil.copyTo(list6, AttachmentVO.class);
                    result.setAttachmentList(addAttachmentList);

                    //审批历史
                    List<ExtSHistoryComment> historyList = sHistoryCommentService.findExtByModelTypeAndRelatedId(
                            HistoryCommentModelTypeEnum.HistoryCommentModelType8.getCode(), flowFormId, null);
                    result.setHistoryList(historyList);

                    restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, result);

                } else {
                    restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
                }
            } else {
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-------biddingDocument-------e-----:" + e.getMessage());
            throw new RuntimeException(e);
        }

        return restResult;
    }

    /**
     * 招标文件操作
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult biddingDocumentOperation(BiddingDocumentRequestVO biddingDocumentRequestVO) {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        try {

            WFlowSubForm wsf = wFlowSubFormService.selectByFormId(biddingDocumentRequestVO.getFlowFormId());
            if (biddingDocumentRequestVO.getActionType() == 2 &&
                    wsf.getBidDocStatus() >= PurchaseNodeButtonStatusEnum.PURCHASE_NODE_3_STATUS_2.getCode()) {
                throw new RuntimeException("不允许重复发起审批！！！", new ServiceThrowable());
            }

            if (biddingDocumentRequestVO != null) {

                if (3 == biddingDocumentRequestVO.getActionType()) { //变更
                    WFlowSubForm wFlowSubForm = new WFlowSubForm();
                    wFlowSubForm.setFlowFormId(biddingDocumentRequestVO.getFlowFormId());
                    wFlowSubForm.setBidDocStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_3_STATUS_1.getCode());
                    wFlowSubForm.setBidDocActionTime(DateUtils.getNow());
                    wFlowSubForm.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);
                    wFlowSubFormService.updateByFormId(wFlowSubForm);

                    String nodeName = sCommentConfigService.getValueByCode(CommentConfigEnum.P_DOC_NODE_NAME_HISTORY_UPDATE.getCode());
                    sHistoryCommentService.saveSHistoryComment(buildCommonHistory(biddingDocumentRequestVO.getFlowFormId(), biddingDocumentRequestVO.getFlowFormId(),
                            HistoryCommentModelTypeEnum.HistoryCommentModelType8.getCode(), "",
                            PurchaseActionNameEnum.PURCHASE_PLAN_3_2.getDesc(), nodeName, 0, false));

                    return new RestReturnResult<Object>(CommonConstants.SUCCESS, "变更成功");
                }

                //招标文件基本信息
                WFlowForm wFlowForm = new WFlowForm();
                wFlowForm.setId(biddingDocumentRequestVO.getFlowFormId());
                wFlowForm.setStartConstructionTime(biddingDocumentRequestVO.getStartConstructionTime());
                wFlowForm.setEndConstructionTime(biddingDocumentRequestVO.getEndConstructionTime());
                wFlowForm.setQualityStandard(biddingDocumentRequestVO.getQualityStandard());
                wFlowForm.setWarrantyPeriod(biddingDocumentRequestVO.getWarrantyPeriod());
                wFlowForm.setPaymentType(biddingDocumentRequestVO.getPaymentType());

                wFlowFormService.updateWFlowForm(wFlowForm);

//				List<SAttachment> newAddedAttachmentList = new ArrayList<SAttachment>();
//
//				//招标文件附件
//				List<AttachmentVO> biddingDocumentAttachmentList = biddingDocumentRequestVO.getBiddingDocumentAttachmentList();
//				if(biddingDocumentAttachmentList != null && biddingDocumentAttachmentList.size() > 0){
//					for(AttachmentVO attachment : biddingDocumentAttachmentList){
//						if(StringUtils.isEmpty(attachment.getId())){
//							SAttachment entity = new SAttachment();
//							BeanUtils.copyProperties(attachment, entity);
//							entity.setFormId(biddingDocumentRequestVO.getFlowFormId());
//							entity.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
//							newAddedAttachmentList.add(entity);
//						}
//					}
//				}
//
//				//图纸附件
//				List<AttachmentVO> drawingAttachmentList = biddingDocumentRequestVO.getDrawingAttachmentList();
//				if(drawingAttachmentList != null && drawingAttachmentList.size() > 0){
//					for(AttachmentVO attachment : drawingAttachmentList){
//						if(StringUtils.isEmpty(attachment.getId())){
//							SAttachment entity = new SAttachment();
//							BeanUtils.copyProperties(attachment, entity);
//							entity.setFormId(biddingDocumentRequestVO.getFlowFormId());
//							entity.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
//							newAddedAttachmentList.add(entity);
//						}
//					}
//				}
//
//				//技术要求和管理要求附件
//				List<AttachmentVO> techAndManageRequirementAttachmentList = biddingDocumentRequestVO.getTechAndManageRequirementAttachmentList();
//				if(techAndManageRequirementAttachmentList != null && techAndManageRequirementAttachmentList.size() > 0){
//					for(AttachmentVO attachment : techAndManageRequirementAttachmentList){
//						if(StringUtils.isEmpty(attachment.getId())){
//							SAttachment entity = new SAttachment();
//							BeanUtils.copyProperties(attachment, entity);
//							entity.setFormId(biddingDocumentRequestVO.getFlowFormId());
//							entity.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
//							newAddedAttachmentList.add(entity);
//						}
//					}
//				}
//
//				//其他附件
//				List<AttachmentVO> otherAttachmentList = biddingDocumentRequestVO.getOtherAttachmentList();
//				if(otherAttachmentList != null && otherAttachmentList.size() > 0){
//					for(AttachmentVO attachment : otherAttachmentList){
//						if(StringUtils.isEmpty(attachment.getId())){
//							SAttachment entity = new SAttachment();
//							BeanUtils.copyProperties(attachment, entity);
//							entity.setFormId(biddingDocumentRequestVO.getFlowFormId());
//							entity.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
//							newAddedAttachmentList.add(entity);
//						}
//					}
//				}
//
//				if(newAddedAttachmentList != null && newAddedAttachmentList.size() > 0){
//					sAttachmentService.insertBatch(newAddedAttachmentList);
//				}

                if (biddingDocumentRequestVO.getActionType() == 2) {//提交
                    // 走审批
                    Map<String, Object> result = sendBpmBidDoc(wFlowFormService.selectById(wFlowForm.getId()));

                    String bpmUrl = String.valueOf(result.get("BPM_URL"));
                    //更新小状态
                    WFlowSubForm wFlowSubForm = new WFlowSubForm();
                    wFlowSubForm.setFlowFormId(biddingDocumentRequestVO.getFlowFormId());
                    if (biddingDocumentRequestVO.getActionType() == 2) {
                        wFlowSubForm.setBidDocStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_3_STATUS_2.getCode());
                        wFlowSubForm.setBidDocActionTime(DateUtils.getNow());
                        updateWfformMbsStatus(biddingDocumentRequestVO.getFlowFormId(), WFlowFormStatusEnum.MBS_BPM_FLAG_2.getCode());
                    } else {
                        wFlowSubForm.setBidDocStatus(PurchaseNodeButtonStatusEnum.PURCHASE_NODE_3_STATUS_1.getCode());
                        wFlowSubForm.setBidDocActionTime(DateUtils.getNow());
                    }
                    wFlowSubFormService.updateByFormId(wFlowSubForm);

                    String nodeName = sCommentConfigService.getValueByCode(CommentConfigEnum.P_DOC_NODE_NAME_HISTORY_LAUNCH.getCode());
                    SHistoryComment historyComment = buildCommonHistory(biddingDocumentRequestVO.getFlowFormId(), biddingDocumentRequestVO.getFlowFormId(),
                            HistoryCommentModelTypeEnum.HistoryCommentModelType8.getCode(), "",
                            PurchaseActionNameEnum.PURCHASE_PLAN_3_1.getDesc(), nodeName, 0, false);
                    historyComment.setCommentUrl(bpmUrl);
                    sHistoryCommentService.saveSHistoryComment(historyComment);
                }

                return new RestReturnResult<Object>(CommonConstants.SUCCESS, "保存/提交成功");

            } else {
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-------biddingDocumentOperation-------e-----:" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

        return restResult;
    }

    /**
     * 发标详情
     */
    @Override
    public RestReturnResult sendBiddingDetails(String flowFormId) throws Exception {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);
        try {
            SendBiddingDetailsResponseVO result = new SendBiddingDetailsResponseVO();
            result.setFlowForm(wFlowFormService.selectById(flowFormId));
            if (StringUtils.isNotEmpty(flowFormId)) {

                //发标单位
                List<ExtWFlowFormSendBid> extWFlowFormSendBidList = wFlowFormSendBidService.getSendBidListByFlowFormId(flowFormId);
                List<SendBiddingUnitVO> sendBiddingUnitVOList = ListObjCopyUtil.copyTo(extWFlowFormSendBidList, SendBiddingUnitVO.class);
                if (sendBiddingUnitVOList != null && sendBiddingUnitVOList.size() > 0) {
                    Map<Integer, List<SendBiddingUnitVO>> sendBiddingUnitDeatils = new HashMap<Integer, List<SendBiddingUnitVO>>();

                    for (SendBiddingUnitVO VO : sendBiddingUnitVOList) {
                        if (sendBiddingUnitDeatils.containsKey(VO.getSegmentsNumber())) {
                            List<SendBiddingUnitVO> list = sendBiddingUnitDeatils.get(VO.getSegmentsNumber());
                            list.add(VO);
                            sendBiddingUnitDeatils.put(VO.getSegmentsNumber(), list);
                        } else {
                            List<SendBiddingUnitVO> list = new ArrayList<SendBiddingUnitVO>();
                            list.add(VO);
                            sendBiddingUnitDeatils.put(VO.getSegmentsNumber(), list);
                        }
                    }

                    result.setSendBiddingUnitDeatils(sendBiddingUnitDeatils);
                }

                //时间节点计划
                WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(flowFormId);
                TimeNodePlanVO timeNodePlanVO = new TimeNodePlanVO();
                BeanUtils.copyProperties(wFlowFormTimeNode, timeNodePlanVO);
                result.setTimeNodePlanVO(timeNodePlanVO);
                restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, result);

            } else {
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-------sendBidDetails-------e-----:" + e.getMessage());
            throw new RuntimeException(e);
        }

        return restResult;
    }

    /**
     * 修改时间节点计划
     *
     * @param timeNodePlanVO
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public RestReturnResult updateTimeNodePlan(TimeNodePlanVO timeNodePlanVO) {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        try {

            if (timeNodePlanVO != null) {

                WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(timeNodePlanVO.getFlowFormId());
                if (wFlowFormTimeNode != null) {

                    WFlowFormTimeNode wFlowFormTimeNodeUpdate = new WFlowFormTimeNode();
                    wFlowFormTimeNodeUpdate.setId(timeNodePlanVO.getId());
                    wFlowFormTimeNodeUpdate.setFlowFormId(timeNodePlanVO.getFlowFormId());
                    wFlowFormTimeNodeUpdate.setSendBid(timeNodePlanVO.getSendBid());
                    wFlowFormTimeNodeUpdate.setExploration(timeNodePlanVO.getExploration());
                    wFlowFormTimeNodeUpdate.setQuestions(timeNodePlanVO.getQuestions());
                    wFlowFormTimeNodeUpdate.setAnswers(timeNodePlanVO.getAnswers());
                    wFlowFormTimeNodeUpdate.setBackBid(timeNodePlanVO.getBackBid());

                    wFlowFormTimeNodeService.updateWFlowFormTimeNode(wFlowFormTimeNodeUpdate);

                    if (wFlowFormTimeNode.getBackBid() != null && timeNodePlanVO.getBackBid().getTime() != wFlowFormTimeNode.getBackBid().getTime()) {//修改了回标截止时间，发送通知
                        WFlowForm wFlowForm = wFlowFormService.selectById(timeNodePlanVO.getFlowFormId());
                        List<String> supplierIdsWithAgree = wFlowFormSupplierEntryService.getSupplierIdsWithAgree(timeNodePlanVO.getFlowFormId());
                        String updateTime = DateUtils.formatDateTime(timeNodePlanVO.getBackBid());
                        for (String id : supplierIdsWithAgree) {
                            SMessageTemplate sMessageTemplate = sMessageTemplateService.getByMsgType(MessagesMsgTypeEnum.MsgType14.getCode());
                            SMessages sMessages = new SMessages();
                            sMessages.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
                            sMessages.setUserIds(id);
                            sMessages.setFlowFormId(timeNodePlanVO.getFlowFormId());
                            sMessages.setReadFlag(CommonConstants.NO_INTEGER);
                            sMessages.setMsgContent(MessageFormat.format(sMessageTemplate.getMsgContent(), wFlowForm.getPurchaseItemName(), updateTime));
                            sMessages.setMsgTitle(MessageFormat.format(sMessageTemplate.getMsgName(), wFlowForm.getPurchaseItemName(), updateTime));
                            sMessages.setMsgType(MessagesMsgTypeEnum.MsgType14.getCode());
                            sMessagesService.insert(sMessages);
                        }
                    }
                }

                restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS);

            } else {
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-------updateTimeNodePlan-------e-----:" + e.getMessage());
            throw new RuntimeException(e);
        }

        return restResult;
    }

    /**
     * 发送内部通知
     */
    @Override
    public RestReturnResult sendIntraNotification(IntraNotificationRequestVO vo) {

        try {

            SMessages message = new SMessages();
            message.setUserIds(vo.getNoticeUserIds());
            message.setMsgType(MessagesMsgTypeEnum.MsgType1.getCode());
            message.setMsgTitle(vo.getNoticeName());
            message.setMsgContent(vo.getNoticeContent());
            message.setFlowFormId(vo.getFlowFormId());
            message.setBidCategoryId(vo.getPurchaseClassification());
            message.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);

            boolean flag = sMessagesService.insert(message);

            if (flag) {
                return new RestReturnResult(CommonConstants.SUCCESS, "内部通知发送成功");
            } else {
                return new RestReturnResult(CommonConstants.FAIL, "内部通知发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("=========sendIntraNotification========e:===" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }

    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * 判断是否在截止时间内（0.在，1不在）
     *
     * @param endTime
     * @param delayTime
     * @return
     */
    Integer isTime(Date endTime, Date delayTime) {
        Integer flag = 0;
        Long now = DateUtils.getNow().getTime();
        if (endTime == null)
            flag = 1;
        else if (delayTime != null) {
            if (delayTime.getTime() < now)
                flag = 1;
        } else if (now > endTime.getTime()) {
            flag = 1;
        }

        return flag;
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult confirmDepositCallBack(List<ConfirmDepositCallBackReqVO> confirmDepositCallBackReqVOList) throws RuntimeException {

        try {

            if (!(confirmDepositCallBackReqVOList != null && confirmDepositCallBackReqVOList.size() > 0)) {
                throw new RuntimeException("传参为空", new ServiceThrowable());
            }

            //保存回调回来的值
            List<SAbutmentLogs> sAbutmentLogsList = new ArrayList<SAbutmentLogs>();
            for (ConfirmDepositCallBackReqVO confirmDepositCallBackReqVO : confirmDepositCallBackReqVOList) {
                SAbutmentLogs sAbutmentLogs = new SAbutmentLogs();
                sAbutmentLogs.setAbutmentType(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_2.getCode());
                sAbutmentLogs.setRelatedId(confirmDepositCallBackReqVO.getForm_id());
                sAbutmentLogs.setAbutmentContent(JSONArray.toJSONString(confirmDepositCallBackReqVOList));
                sAbutmentLogs.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);
                sAbutmentLogsList.add(sAbutmentLogs);
            }
            sAbutmentLogsService.insertBatch(sAbutmentLogsList);

            //采招系统逻辑处理
            for (ConfirmDepositCallBackReqVO confirmDepositCallBackReqVO : confirmDepositCallBackReqVOList) {

                if (StringUtils.isBlank(confirmDepositCallBackReqVO.getForm_id())
                        || StringUtils.isBlank(confirmDepositCallBackReqVO.getSupplier_id())) {
                    throw new RuntimeException("传参采购id/供方id为空", new ServiceThrowable());
                }

                ExtWFlowFormCashDeposit extWFlowFormCashDepositDB = wFlowFormCashDepositService.getExtByFormIdAndSupplierId(confirmDepositCallBackReqVO.getForm_id(), confirmDepositCallBackReqVO.getSupplier_id());
                if (extWFlowFormCashDepositDB == null) {
                    throw new RuntimeException("供应商入围-保证金确认记录不存在", new ServiceThrowable());
                }

                extWFlowFormCashDepositDB.setCashierConfirmStatus(confirmDepositCallBackReqVO.getCashier_confirm_status());
                extWFlowFormCashDepositDB.setRefundBidBondsFlag(CommonConstants.NO_INTEGER);
                extWFlowFormCashDepositDB.setUpdateDate(DateUtils.parse(confirmDepositCallBackReqVO.getConfirm_time(), "yyyy-MM-dd hh:mm:ss"));
                extWFlowFormCashDepositDB.setUpdateBy(UserUtils.getCurrentUserId());

                wFlowFormCashDepositService.updateById(extWFlowFormCashDepositDB);
            }

            //注意：对接1:执行成功,0:执行失败
            return new RestReturnResult(CommonConstants.SUCCESS, "执行成功");


        } catch (Exception e) {
            e.printStackTrace();
            logger.error("============confirmDepositCallBack==========e:====" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult drawBackDepositCallBack(
            List<DrawBackDepositCallBackReqVO> drawBackDepositCallBackReqVOList) throws RuntimeException {
        try {
            Gson gson = new Gson();
            if (!(drawBackDepositCallBackReqVOList != null && drawBackDepositCallBackReqVOList.size() > 0)) {
                throw new RuntimeException("传参为空", new ServiceThrowable());
            }

            System.out.println("============drawBackDepositCallBack=======[params]=========" + gson.toJson(drawBackDepositCallBackReqVOList));

            //保存回调回来的值
            List<SAbutmentLogs> sAbutmentLogsList = new ArrayList<SAbutmentLogs>();
            for (DrawBackDepositCallBackReqVO drawBackDepositCallBackReqVO : drawBackDepositCallBackReqVOList) {
                SAbutmentLogs sAbutmentLogs = new SAbutmentLogs();
                sAbutmentLogs.setAbutmentType(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_4.getCode());
                sAbutmentLogs.setRelatedId(drawBackDepositCallBackReqVO.getForm_id());
                sAbutmentLogs.setAbutmentContent(JSONArray.toJSONString(drawBackDepositCallBackReqVOList));
                sAbutmentLogs.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);
                sAbutmentLogsList.add(sAbutmentLogs);
            }
            sAbutmentLogsService.insertBatch(sAbutmentLogsList);

            //采招系统逻辑处理
            for (DrawBackDepositCallBackReqVO drawBackDepositCallBackReqVO : drawBackDepositCallBackReqVOList) {

                if (StringUtils.isBlank(drawBackDepositCallBackReqVO.getForm_id())
                        || StringUtils.isBlank(drawBackDepositCallBackReqVO.getSupplier_id())) {
                    throw new RuntimeException("传参采购id/供方id为空", new ServiceThrowable());
                }

                ExtWFlowFormCashDeposit extWFlowFormCashDepositDB = wFlowFormCashDepositService.getExtByFormIdAndSupplierId(drawBackDepositCallBackReqVO.getForm_id(), drawBackDepositCallBackReqVO.getSupplier_id());
                if (extWFlowFormCashDepositDB == null) {
                    throw new RuntimeException("供应商入围-保证金确认记录不存在", new ServiceThrowable());
                }

                extWFlowFormCashDepositDB.setRefundBidBondsFlag(CommonConstants.YES_INTEGER);
                extWFlowFormCashDepositDB.setRefundCashierStatus(drawBackDepositCallBackReqVO.getRefund_cashier_status());
                extWFlowFormCashDepositDB.setUpdateDate(DateUtils.parse(drawBackDepositCallBackReqVO.getConfirm_time(), "yyyy-MM-dd hh:mm:ss"));
                extWFlowFormCashDepositDB.setUpdateBy(UserUtils.getCurrentUserId());

                wFlowFormCashDepositService.updateById(extWFlowFormCashDepositDB);
            }

            //注意：对接1:执行成功,0:执行失败
            return new RestReturnResult(CommonConstants.SUCCESS, "执行成功");

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("============drawBackDepositCallBack==========e:====" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }

    /***
     * MBS回调公共接口
     * @param mbsCommonCallBackReqVOList
     * @return
     * @throws RuntimeException
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult mbsCommonCallBack(List<MbsCommonCallBackReqVO> mbsCommonCallBackReqVOList) throws RuntimeException {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);
        try {
            System.out.println("============mbsCommonCallBack=======[params]=========" + mbsCommonCallBackReqVOList);
            Gson gson = new Gson();
            if (CollectionUtils.isEmpty(mbsCommonCallBackReqVOList)) {
                throw new RuntimeException("传参为空", new ServiceThrowable());
            }
            System.out.println("============mbsCommonCallBack=======[params]=========" + gson.toJson(mbsCommonCallBackReqVOList));

            //采招系统逻辑处理
            boolean isDone = false;
            String type = mbsCommonCallBackReqVOList.get(0).getType();
            if (StringUtils.equalsIgnoreCase(MBSCommonTypeEnum.MBSCommonTypeEnum_SourcingDeposit.getCode(), type)) {
                //收/退保证金
                mbsSourcingDepositCallBack(mbsCommonCallBackReqVOList);
                isDone = true;
            } else {
                mbsSourcingCommonCallBack(mbsCommonCallBackReqVOList);
                isDone = true;
            }
            //注意：对接1:执行成功,0:执行失败
            if (isDone) {
                restResult = new RestReturnResult(CommonConstants.SUCCESS, "执行成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
        return restResult;
    }

    /***
     * 收/退保证金回调接口
     * @param mbsCommonCallBackReqVOList
     */
    private void mbsSourcingDepositCallBack(List<MbsCommonCallBackReqVO> mbsCommonCallBackReqVOList) {
        Gson gson = new Gson();
        if (CollectionUtils.isNotEmpty(mbsCommonCallBackReqVOList)) {
            for (MbsCommonCallBackReqVO mbsCommonCallBackReqVO : mbsCommonCallBackReqVOList) {
                if (StringUtils.isBlank(mbsCommonCallBackReqVO.getUuid())) {
                    throw new RuntimeException("业务uuid为空", new ServiceThrowable());
                }

                if (StringUtils.isBlank(mbsCommonCallBackReqVO.getSdId())) {
                    throw new RuntimeException("sdId为空", new ServiceThrowable());
                }

                WFlowFormCashDeposit wFlowFormCashDepositDB = wFlowFormCashDepositService.selectById(mbsCommonCallBackReqVO.getUuid());
                if (wFlowFormCashDepositDB == null) {
                    throw new RuntimeException("供应商入围-保证金确认记录不存在", new ServiceThrowable());
                }

                //收保证金
                if (StringUtils.equalsIgnoreCase(MBSCommonStatusEnum.MBSCommonStatusEnum_B.getCode(), mbsCommonCallBackReqVO.getStatus())) {
                    wFlowFormCashDepositDB.setCashierConfirmStatus(CashierConfirmStatusEnum.CONFIRMED.getCode());
                    wFlowFormCashDepositDB.setAccSynId(mbsCommonCallBackReqVO.getSdId());
                    wFlowFormCashDepositDB.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);

                    wFlowFormCashDepositService.updateById(wFlowFormCashDepositDB);

//					//更新发起对接日志
//					sAbutmentLogsService.updateAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_1.getCode(),
//							mbsCommonCallBackReqVO.getUuid(), 1, 0);

                    //保存当前回调日志
                    sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_2.getCode(),
                            mbsCommonCallBackReqVO.getUuid(), gson.toJson(mbsCommonCallBackReqVOList), 1, 0);
                }

                //退保证金
                if (StringUtils.equalsIgnoreCase(MBSCommonStatusEnum.MBSCommonStatusEnum_D.getCode(), mbsCommonCallBackReqVO.getStatus())) {
                    wFlowFormCashDepositDB.setRefundBidBondsFlag(CommonConstants.YES_INTEGER);
                    wFlowFormCashDepositDB.setRefundCashierStatus(RefundCashierStatusEnum.REFUNDED.getCode());
                    wFlowFormCashDepositDB.setAccSynId(mbsCommonCallBackReqVO.getSdId());
                    wFlowFormCashDepositDB.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);

                    wFlowFormCashDepositService.updateById(wFlowFormCashDepositDB);

                    //更新发起对接日志
//					sAbutmentLogsService.updateAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_3.getCode(),
//							mbsCommonCallBackReqVO.getUuid(), 1, 0);

                    //保存当前回调日志
                    sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_4.getCode(),
                            mbsCommonCallBackReqVO.getUuid(), gson.toJson(mbsCommonCallBackReqVOList), 1, 0);
                }
            }
        }
    }

    /**
     * mb回调
     *
     * @param mbsCommonCallBackReqVOList
     */
    private void mbsSourcingCommonCallBack(List<MbsCommonCallBackReqVO> mbsCommonCallBackReqVOList) {
        Gson gson = new Gson();
        if (CollectionUtils.isNotEmpty(mbsCommonCallBackReqVOList)) {
            for (MbsCommonCallBackReqVO mbsCommonCallBackReqVO : mbsCommonCallBackReqVOList) {
                if (StringUtils.isBlank(mbsCommonCallBackReqVO.getUuid())) {
                    throw new RuntimeException("业务uuid为空", new ServiceThrowable());
                }
                purchaseMbsCallBack(mbsCommonCallBackReqVO, mbsCommonCallBackReqVOList);
            }
        }
    }


    /**
     * 变更经办人
     *
     * @param updateOperatorVO
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void updateOperator(UpdateOperatorVO updateOperatorVO) {
        Integer planStatus = 0;
        if (updateOperatorVO.getType() == PurchaseCommonEnum.PURCHASE_PLAN_TYPE_SPECIAL.getCode()) {
            PSpecialPurchasePlan pSpecialPurchasePlan = pSpecialPurchasePlanService.selectById(updateOperatorVO.getId());
            planStatus = pSpecialPurchasePlan.getPlanStatus();
//			if(pSpecialPurchasePlan.getPlanStatus()!=PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_4.getCode()&&
//					pSpecialPurchasePlan.getPlanStatus()!=PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_3.getCode()){
//				throw new RuntimeException("状态已更新，请刷新页面",new ServiceThrowable());
//			}
            pSpecialPurchasePlan.setHandleUser(updateOperatorVO.getUserId());
            pSpecialPurchasePlanService.updateById(pSpecialPurchasePlan);
        } else {
            PStrategicPurchaseContact pStrategicPurchaseContact = pStrategicPurchaseContactService.selectById(updateOperatorVO.getId());
            planStatus = pStrategicPurchaseContact.getPurchaseItemStatus();
//			if(pStrategicPurchaseContact.getPurchaseItemStatus()!=PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_4.getCode()&&
//					pStrategicPurchaseContact.getPurchaseItemStatus()!=PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_3.getCode()){
//				throw new RuntimeException("状态已更新，请刷新页面",new ServiceThrowable());
//			}
            pStrategicPurchaseContact.setHandleUser(updateOperatorVO.getUserId());
            pStrategicPurchaseContactService.updateById(pStrategicPurchaseContact);
        }

        if (planStatus == PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_4.getCode()) {
            EntityWrapper<WFlowForm> entityWrapper = new EntityWrapper<WFlowForm>();
            entityWrapper.setSqlSelect("id,handle_user").and("abortive_flag!={0}", CommonConstants.ABORTIVE_BID_OK).
                    eq("purchase_plan_id", updateOperatorVO.getId()).eq("del_flag", CommonConstants.DEL_FLAG_NORMAL);

            List<WFlowForm> wFlowForms = wFlowFormService.selectList(entityWrapper);
            if (CollectionUtils.isEmpty(wFlowForms) || wFlowForms.size() > 1) {
                throw new RuntimeException("采购数据异常，一个计划对应多个采购流程，请联系管理人员", new ServiceThrowable());
            }
            WFlowForm updateWflowForm = wFlowForms.get(0);
            String oldHandler = updateWflowForm.getHandleUser();
            if (StringUtils.isEmpty(oldHandler) || StringUtils.isEmpty(updateWflowForm.getId())) {
                throw new RuntimeException("参数异常", new ServiceThrowable());
            }
            SMyDeals sMyDealsWhere = new SMyDeals();
            sMyDealsWhere.setDoneFlag(CommonConstants.UNDONG_FLAG);
            sMyDealsWhere.setRelatedId(updateWflowForm.getId());
            sMyDealsWhere.setUserId(oldHandler);
            sMyDealsService.updateUserByEntity(updateOperatorVO.getUserId(), sMyDealsWhere);
            updateWflowForm.setHandleUser(updateOperatorVO.getUserId());
            wFlowFormService.updateById(updateWflowForm);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeExcepon", "Exception"})
    public String uploadStrategicProtocol(InputStream in) {

        List<List<Object>> data = ExcelUtils.readBPExcel(in);
        checkExcelHearder(data.get(0));
        String userId = UserUtils.getCurrentUserId();

        List<Integer> errnums = Lists.newArrayList();
        if (CollectionUtils.isEmpty(data) || CollectionUtils.isEmpty(data.get(0))) {
            throw new RuntimeException("导入数据无内容", new ServiceThrowable());
        }
        List<WStrategicProtocol> wStrategicProtocols = Lists.newArrayListWithCapacity(data.size());
        Map<String, String> cacheSuplier = Maps.newHashMap();
        SSuppliers supplier = new SSuppliers();
        int i = -1;
        for (List<Object> object : data) {
            i++;
            if (i == 0 || object.size() != 5) {
                continue;
            }

            WStrategicProtocol wStrategicProtocol = new WStrategicProtocol();
            if (object.get(0) != null)
                wStrategicProtocol.setStrategicCategoryName(String.valueOf(object.get(0)));
            if (object.get(1) != null) {
                wStrategicProtocol.setSupplierName(String.valueOf(object.get(1)));
                if (cacheSuplier.get(wStrategicProtocol.getSupplierName()) != null) {
                    wStrategicProtocol.setSupplierId(cacheSuplier.get(wStrategicProtocol.getSupplierName()));
                } else {
                    supplier.setCompanyName(wStrategicProtocol.getSupplierName());
                    List<SSuppliers> sSuppliers = sSuppliersService.selectList(new EntityWrapper<>(supplier));
                    if (CollectionUtils.isNotEmpty(sSuppliers)) {
                        wStrategicProtocol.setSupplierId(sSuppliers.get(0).getId());
                        cacheSuplier.put(wStrategicProtocol.getSupplierName(), wStrategicProtocol.getSupplierId());
                    } else {
                        throw new RuntimeException("第" + i + "行发生错误：供应商不存在", new ServiceThrowable());
                    }
                }
            }
            if (object.get(4) != null)
                wStrategicProtocol.setContractCode(String.valueOf(object.get(4)));
            if (object.get(5) != null)
                wStrategicProtocol.setStrategicName(String.valueOf(object.get(5)));
            if (object.get(2) != null)
                wStrategicProtocol.setProtocolStartTime(DateUtils.parseDate(object.get(2)));
            if (object.get(3) != null)
                wStrategicProtocol.setProtocolEndTime(DateUtils.parseDate(object.get(3)));
            wStrategicProtocol.setStrategicStatus(1);
            wStrategicProtocol.setBaseFeilds(userId, "", CommonConstants.DEL_FLAG_NORMAL, true);
            if (org.apache.commons.lang3.StringUtils.isEmpty(wStrategicProtocol.getSupplierName().trim()) || org.apache.commons.lang3.StringUtils.isEmpty(wStrategicProtocol.getContractCode().trim())) {
                throw new RuntimeException("第" + i + "行发生错误：供应商和合同编号必填", new ServiceThrowable());
            }
            if (!wStrategicProtocolService.checkRepeat(wStrategicProtocol)) {
                //throw new RuntimeException("导入数据和已存在数据库中的数据重复-"+wStrategicProtocol.getSupplierName()+"-"+wStrategicProtocol.getContractCode());
                wStrategicProtocols.add(wStrategicProtocol);
            }

        }
        if (CollectionUtils.isNotEmpty(wStrategicProtocols))
            wStrategicProtocolService.insertBatch(wStrategicProtocols);
        String errMsg = "";
//		if(errnums.size()>0){
//			errMsg = "发生错误行号：";
//			for(Integer num:errnums){
//				errMsg+=num+" ";
//			}
//		}
        return "";

    }

    public void checkExcelHearder(List<Object> hearder) {
//		if(!String.valueOf(hearder.get(0)).equals("strategic_category_name")){
//			throw new RuntimeException("导入的Excel不匹配！",new ServiceThrowable());
//		}

        if (hearder.size() != 5) {
            throw new RuntimeException("导入的Excel不匹配！", new ServiceThrowable());
        }
    }

    @Override
    public void updateStrategicProtocol(WStrategicProtocol wStrategicProtocol) {
        wStrategicProtocolService.updateById(wStrategicProtocol);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public void releaseContract(AssociateContractVO form) {
        WFlowForm db = wFlowFormService.selectById(form.getId());
        PSpecialPurchasePlan dbPSpecialPurchasePlan = pSpecialPurchasePlanService.selectById(db.getPurchasePlanId());

        wFlowFormService.clearContractById(form.getId());

        PSpecialPurchasePlan pSpecialPurchasePlan = pSpecialPurchasePlanService.getSpecialPurchasePlanById(db.getPurchasePlanId());
        pSpecialPurchasePlan.setId(db.getPurchasePlanId());
        pSpecialPurchasePlan.setContractId("");
        pSpecialPurchasePlan.setContractCode("");
        pSpecialPurchasePlan.setContractName("");
        pSpecialPurchasePlan.setProjectByStage("");
        pSpecialPurchasePlan.setContactPlanId("");

        pSpecialPurchasePlanService.updateById(pSpecialPurchasePlan);

        if (dbPSpecialPurchasePlan.getContactPlanId() != null) {
            //将之前关联的招标项释放
            String[] dbcontactPlanIdArr = dbPSpecialPurchasePlan.getContactPlanId().split(",");
            List<String> dbcontactPlanIdList = Arrays.asList(dbcontactPlanIdArr);
            List<PContactPlan> oldpContactPlanList = pContactPlanService.selectBatchIds(dbcontactPlanIdList);
            if (oldpContactPlanList != null && oldpContactPlanList.size() > 0) {
                for (PContactPlan pContactPlan : oldpContactPlanList) {

                    pContactPlan.setPlanStatus(CommonConstants.GENERATED_NO);//专项采购计划已生成
                    pContactPlan.setPurchaseItemName("");//设置采购项ID
                    pContactPlan.setBaseFeilds("", null, CommonConstants.NO_INTEGER, false);
                }
                pContactPlanService.updateBatchById(oldpContactPlanList);
            }
        }

    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public void deleteContract(AssociateContractVO form) {
        //判断是否被使用，采购计划是否已经发起定标流程，发起定标流程后不允许删除操作；
        PContactPlan contactPlan = pContactPlanService.selectById(form.getId());
        if (StringUtils.isNotEmpty(contactPlan.getPurchaseItemName())) {
            PSpecialPurchasePlan dbPSpecialPurchasePlan = pSpecialPurchasePlanService.selectById(contactPlan.getPurchaseItemName());
            if (dbPSpecialPurchasePlan != null) {
                WFlowForm wFlowForm = new WFlowForm();
                wFlowForm.setPurchasePlanId(dbPSpecialPurchasePlan.getId());
                EntityWrapper entityWrapper = new EntityWrapper<WFlowForm>();
                entityWrapper.setEntity(wFlowForm);
                List<WFlowForm> wfFormList = wFlowFormService.selectList(entityWrapper);
                if (wfFormList != null && wfFormList.size() > 0) {
                    for (int i = 0; i < wfFormList.size(); i++) {
                        WFlowForm wfFormItem = wfFormList.get(i);
                        if (String.valueOf(WFlowFormStatusEnum.WFLOW_FROM_STATUS_2.getCode()).equals(wfFormItem.getFlowFormStatus())) {
                            //已定标不允许删除
                            throw new RuntimeException("已定标不允许删除", new ServiceThrowable());
                        } else if (String.valueOf(WFlowFormStatusEnum.WFLOW_FROM_STATUS_3.getCode()).equals(wfFormItem.getFlowFormStatus())) {
                            //已流程标不处理。
                        } else {
                            //进行中，判断是否已经发起定标流程。
                            if (String.valueOf(WorkFlowLineStatusEnum.LINE_STATUS_CALIBRATION_BID).equals(wfFormItem.getFlowFormSubStatus())
                                    && !String.valueOf(WFlowFormStatusEnum.MBS_BPM_FLAG_1.getCode()).equals(wfFormItem.getMbsBpmFlag())
                            ) {
                                throw new RuntimeException("已发起定标流程不允许删除", new ServiceThrowable());
                            } else {
                                AssociateContractVO wfForm = new AssociateContractVO();
                                wfForm.setId(wfFormItem.getId());
                                //释放招标项
                                this.releaseContract(wfForm);
                            }
                        }
                    }
                }
            }
        }

        //删除合约规划，并调用成本系统接口，释放招标项。
        boolean result = synDataService.deletemergeContract(contactPlan.getContractId(), contactPlan.getContractDetailId());
        if (!result) {
            throw new RuntimeException("调用成本系统接口失败", new ServiceThrowable());
        }
        pContactPlanService.deleteById(form.getId());

    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public void associateContract(AssociateContractVO form) {
        WFlowForm db = wFlowFormService.selectById(form.getId());
        PSpecialPurchasePlan dbPSpecialPurchasePlan = pSpecialPurchasePlanService.selectById(db.getPurchasePlanId());

        WFlowForm wFlowForm = new WFlowForm();
        BeanUtils.copyProperties(form, wFlowForm);
        wFlowFormService.updateById(wFlowForm);


        if (dbPSpecialPurchasePlan.getContactPlanId() != null) {
            //将之前关联的招标项释放
            String[] dbcontactPlanIdArr = dbPSpecialPurchasePlan.getContactPlanId().split(",");
            List<String> dbcontactPlanIdList = Arrays.asList(dbcontactPlanIdArr);
            List<PContactPlan> oldpContactPlanList = pContactPlanService.selectBatchIds(dbcontactPlanIdList);
            if (oldpContactPlanList != null && oldpContactPlanList.size() > 0) {
                for (PContactPlan pContactPlan : oldpContactPlanList) {

                    pContactPlan.setPlanStatus(CommonConstants.GENERATED_NO);//专项采购计划已生成
                    pContactPlan.setPurchaseItemName(null);//设置采购项ID
                    pContactPlan.setBaseFeilds("", null, CommonConstants.NO_INTEGER, false);

                }
                pContactPlanService.updateBatchById(oldpContactPlanList);
            }
        }


        Double planBudgetPrices = 0.00d;




        //更新招标项锁定状态
        String[] contactPlanIdArr = form.getContactPlanId().split(",");
        List<String> contactPlanIdList = Arrays.asList(contactPlanIdArr);

        List<PContactPlan> pContactPlanList = pContactPlanService.selectBatchIds(contactPlanIdList);

        if (pContactPlanList != null && pContactPlanList.size() > 0) {
            for (PContactPlan pContactPlan : pContactPlanList) {
                if (pContactPlan.getPlanStatus() == CommonConstants.GENERATED_YES) {
                    throw new RuntimeException("该合约已经生成过计划", new ServiceThrowable());
                }
                pContactPlan.setPlanStatus(CommonConstants.GENERATED_YES);//专项采购计划已生成
                pContactPlan.setPurchaseItemName(db.getPurchasePlanId());//设置采购项ID
                pContactPlan.setBaseFeilds("", null, CommonConstants.NO_INTEGER, false);
                if (pContactPlan.getPlanBudgetPrices() != null) {
                    planBudgetPrices += pContactPlan.getPlanBudgetPrices();
                }
            }
            pContactPlanService.updateBatchById(pContactPlanList);
        }
        PSpecialPurchasePlan pSpecialPurchasePlan = pSpecialPurchasePlanService.getSpecialPurchasePlanById(db.getPurchasePlanId());
        pSpecialPurchasePlan.setId(db.getPurchasePlanId());
        pSpecialPurchasePlan.setContractId(form.getContractId());
        pSpecialPurchasePlan.setContractCode(form.getContractCode());
        pSpecialPurchasePlan.setContactPlanId(form.getContactPlanId());
        pSpecialPurchasePlan.setContractName(form.getContractName());
        pSpecialPurchasePlan.setProjectByStage(form.getProjectByStage());
        pSpecialPurchasePlan.setPlanBudgetPrices(planBudgetPrices);

        pSpecialPurchasePlanService.updateById(pSpecialPurchasePlan);

    }

    @Override
    public void saveCalibrationConclusion(CalibrationInfoReqVO calibrationInfoReqVO) {
        WFlowForm wFlowForm = new WFlowForm();
        wFlowForm.setId(calibrationInfoReqVO.getFlowFormId());
        wFlowForm.setCalibrationConclusion(calibrationInfoReqVO.getCalibrationConclusion());
        wFlowFormService.updateById(wFlowForm);
    }
}


//	/***
//	 * 招标文件
//	 * @param mbsCommonCallBackReqVOList
//	 */
//	private void mbsSourcingFileCallBack(List<MbsCommonCallBackReqVO> mbsCommonCallBackReqVOList){
//		Gson gson = new Gson();
//		if(CollectionUtils.isNotEmpty(mbsCommonCallBackReqVOList)){
//			for(MbsCommonCallBackReqVO mbsCommonCallBackReqVO : mbsCommonCallBackReqVOList){
//				if(StringUtils.isBlank(mbsCommonCallBackReqVO.getUuid())){
//					throw new RuntimeException("业务uuid为空", new ServiceThrowable());
//				}
//
//				//TODO
//
//			}
//		}
//	}
//
//	/**
//	 * 定标
//	 * @param mbsCommonCallBackReqVOList
//	 */
//	private void mbsSourcingDecisionCallBack(List<MbsCommonCallBackReqVO> mbsCommonCallBackReqVOList){
//		Gson gson = new Gson();
//		if(CollectionUtils.isNotEmpty(mbsCommonCallBackReqVOList)){
//			for(MbsCommonCallBackReqVO mbsCommonCallBackReqVO : mbsCommonCallBackReqVOList){
//				if(StringUtils.isBlank(mbsCommonCallBackReqVO.getUuid())){
//					throw new RuntimeException("业务uuid为空", new ServiceThrowable());
//				}
//
//				//TODO
//			}
//		}
//	}
//}

